简体   繁体   中英

UniswapV2 swapExactTokensForETH approve and transfer

I have tried to create a smart contract. I followed this tutorial to have uniswap swap examples https://cryptomarketpool.com/how-to-swap-tokens-on-uniswap-using-a-smart-contract/

Here one of my smart contract function in which I would like to swap some token amount for some eth.

  function swapTokenToEth(uint tokenAmount, uint amountOutMin) public {
    uint deadline = block.timestamp + 150;
    IERC20(token).transferFrom(msg.sender, address(this), tokenAmount);
    IERC20(token).approve(UNISWAP_V2_ROUTER, tokenAmount);
    uniswapRouter.swapExactTokensForETH(tokenAmount, amountOutMin, getPath(), msg.sender, deadline);
  }

I am calling this swap method from a Truffle test environment

await dex.swapTokenToEth(tokenAmount, amountOutMin {
  from: accounts[1],
});

I keep getting this error:

Error: Returned error: VM Exception while processing transaction: revert ERC20: transfer amount exceeds allowance -- Reason given: ERC20: transfer amount exceeds allowance.

I tried several things but now I am stuck and I don't understand this error. Any hint on how to solve this?

ERC20: transfer amount exceeds allowance

This is a custom error message from a contract.

Based on the context, I'm assuming it's coming from the token contract's function transferFrom() (or another function called by this one), from a failed require() condition.

Which means that the accounts[1] (user executing the swapTokenToEth() function) haven't approved the dex contract to manipulate their tokens.

Solution: Before executing dex.swapTokenToEth() , you also need to execute tokenContract.approve(dexAddress) from the accounts[1] address. It's sufficient to execute the approve() function just once (unless you redeploy the contracts) with a sufficient amount - the approval decreases with each amount used in the transferFrom() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM