Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to withdraw all tokens from the my contract in solidity

Can anyone help me?

I created a basic contract.But don't know the withdrawal function.Please help me.Thanks everyone I tried creating a basic function but it doesn't work

function withdraw() public {
    msg.sender.transfer(address(this).balance);
}
like image 452
learn code Avatar asked Jan 25 '23 07:01

learn code


1 Answers

payable(msg.sender).transfer(address(this).balance);

This line withdraws the native balance (ETH if your contract is on Ethereum network).


To withdraw a token balance, you need to execute the transfer() function on the token contract. So in order to withdraw all tokens, you need to execute the transfer() function on all token contracts.

You can create a function that withdraws any ERC-20 token based on the token contract address that you pass as an input.

pragma solidity ^0.8;

interface IERC20 {
    function transfer(address _to, uint256 _amount) external returns (bool);
}

contract MyContract {
    function withdrawToken(address _tokenContract, uint256 _amount) external {
        IERC20 tokenContract = IERC20(_tokenContract);
        
        // transfer the token from address of this contract
        // to address of the user (executing the withdrawToken() function)
        tokenContract.transfer(msg.sender, _amount);
    }
}

Mind that this code is unsafe - anyone can execute the withdrawToken() funciton. If you want to run it in production, add some form of authentication, for example the Ownable pattern.

Unfortunately, because of how token standards (and the Ethereum network in general) are designed, there's no easy way to transfer "all tokens at once", because there's no easy way to get the "non-zero token balance of an address". What you see in the blockchain explorers (e.g. that an address holds tokens X, Y, and Z) is a result of an aggregation that is not possible to perform on-chain.

like image 50
Petr Hejda Avatar answered Feb 13 '23 08:02

Petr Hejda