How to withdraw Ether from a contract

Hello, I hope it’s okay to respond on such an old guide!

I tried this out and it worked great for any tokens, but failed every time for ETH. Is it possible to do the same thing with ETH directly? I want to be able to send ETH and any tokens to MyContract.sol via the contract address, then be able to call withdraw and withdraw ETH or a token of my choosing.

1 Like

I think the library SafeERC20 is for ERC20 token, so for eth, there is something different, it should be like this:

function withdrawETH(address payable recipient, uint256 amount) public {
    (bool succeed, bytes memory data) = recipient.call{value: amount}("");
    require(succeed, "Failed to withdraw Ether");
}
1 Like

That makes sense, but I’m unable to send ETH to it directly as well (i.e. just sending ETH to the contract address will always return Out of Gas, while sending ERC20 tokens to it works fine).

I think I’m approaching this wrong anyways, as I’ve read in other posts about the non-uniformity between ETH and tokens and how there’s no real solution just yet to gracefully handle both. Thank you!

1 Like

If you only want to receive eth, you should add a function like following:

receive() external payable {}

And for more details about transfer and send eth, you can have a look at this article: https://solidity-by-example.org/sending-ether/

1 Like

Thanks so much, it worked beautifully. I appreciate your help!

1 Like