[英]How can my smart contract swap WETH for ETH?
My smart contract receives WETH.我的智能合约收到 WETH。 I want to create a function anyone can run to convert the WETH into ETH.我想创建一个 function 任何人都可以运行以将 WETH 转换为 ETH。
That's the code I have那是我的代码
function swapWeth() public nonReentrant {
uint balanceWETH = IWETH(WETH).balanceOf(address(this));
if (balanceWETH > 0) {
IERC20(WETH).approve(address(this), balanceWETH);
IWETH(WETH).withdraw(balanceWETH);
}
}
When I call the function I always get the following message and my transaction never goes through.当我拨打 function 时,我总是收到以下消息,而且我的交易从未完成。
We were not able to estimate gas.我们无法估计气体。 There might be an error in the contract and this transaction may fail.合约中可能存在错误,此交易可能会失败。
How do I debug this?我该如何调试?
I just want to call the withdraw
function of the WETH smart contract to swap my contracts's WETH into ETH.我只想调用WETH智能合约的withdraw
function,将我合约的WETH兑换成ETH。 The user initiating the transaction just pays for the gas fee.发起交易的用户只需支付gas费。
I just want to convert my contract's WETH into ETH.我只想将我合约的 WETH 转换成 ETH。
Any help would be appreciated.任何帮助,将不胜感激。
Thanks谢谢
Edit : I changed the code to this and it still fails.编辑:我将代码更改为此,但它仍然失败。 I'm on Goerli.我在歌尔里Does someone has a working example?有人有工作的例子吗?
function withdrawETH() public {
address WETH9 = 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6; // Goerli
uint balanceWETH = IERC20(WETH9).balanceOf(address(this));
IWETH9(WETH9).withdraw(balanceWETH);
}
Contract address: https://goerli.etherscan.io/address/0xd9e84819483410b08ec24320eb88acfc4ee6e8c8合约地址: https://goerli.etherscan.io/address/0xd9e84819483410b08ec24320eb88acfc4ee6e8c8
Edit : See Petr's response and comments bellow.编辑:请参阅下面 Petr 的回复和评论。 The problem was with my 'receive' function问题出在我的“接收”function
IERC20(WETH).approve(address(this), balanceWETH);
This line gives approval这条线给予批准
approve()
function来自你的合约地址——这是调用approve()
function 的地址address(this)
到你的合同地址 - 第一个参数,值address(this)
The approval is given by the address that executes the approve()
function.通过执行approve()
的地址 function 给出批准。
If you want to get approval from the user, they need to invoke the approve()
function directly on the WETH
contract in a separate transaction - not through your contract.如果您想获得用户的批准,他们需要在单独的交易中直接在WETH
合约上调用approve()
function - 而不是通过您的合约。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.