[英]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/
我按照本教程获得了 uniswap 交换示例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 之一,我想将一些代币金额换成一些 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我从 Truffle 测试环境中调用此交换方法
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
ERC20:转账金额超过限额
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.根据上下文,我假设它来自
token
合约的 function transferFrom()
(或另一个由这个调用的 function ),来自失败的require()
条件。
Which means that the accounts[1]
(user executing the swapTokenToEth()
function) haven't approved the dex
contract to manipulate their tokens.这意味着
accounts[1]
(执行swapTokenToEth()
函数的用户)尚未批准dex
合约来操纵他们的代币。
Solution: Before executing dex.swapTokenToEth()
, you also need to execute tokenContract.approve(dexAddress)
from the accounts[1]
address.解决方案:在执行
dex.swapTokenToEth()
之前,还需要从accounts[1]
地址执行tokenContract.approve(dexAddress)
。 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.只需执行一次approval
approve()
function 就足够了(除非您重新部署合同),并且有足够的金额 - 批准会随着transferFrom()
function 中使用的每个金额而减少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.