0

I'm trying to implement something like this (which works)

function withdraw() public {
    msg.sender.transfer(address(this).balance)
}

but I need to be able to withdraw ERC20 tokens other than Ethereum from my contract, is this possible? I can't seem to figure it out.

Thanks!

  • A problem with the code snippet is that it is not permissioned so anyone will be able to extract ethers from the contract. – Ismael Jul 8 at 1:41
1
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

function withdrawErc20(IERC20 token) public {
  token.transfer(msg.sender, token.balanceOf(address(this));
}

See IERC20 for the interface code. Copy & paste it or install it via npm.

| improve this answer | |
  • Works amazingly! Thank you so much! – Robert Jul 8 at 2:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.