learn code
learn code

Reputation: 91

how to withdraw all tokens from the my contract in solidity

I created a basic contract. But don't know the withdrawal function.

I tried creating a basic function but it doesn't work

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

Upvotes: 9

Views: 33036

Answers (4)

Maxim Vasilkov
Maxim Vasilkov

Reputation: 71

I came here to find a solution to allow the owner to withdraw any token which accidentally can be sent to the address of my smart contract. I believe it can be useful for others:

 /**
 * @dev transfer the token from the address of this contract  
 * to address of the owner 
 */
function withdrawToken(address _tokenContract, uint256 _amount) external onlyOwner {
    IERC20 tokenContract = IERC20(_tokenContract);

    // needs to execute `approve()` on the token contract to allow itself the transfer
    tokenContract.approve(address(this), _amount);

    tokenContract.transferFrom(address(this), owner(), _amount);
}

Upvotes: 2

Yilmaz
Yilmaz

Reputation: 49671

  • Since it is a basic contract, I assume it is not erc20 token and if you just want to withdraw money:

    function withdraw(uint amount) external onlyOwner{
       (bool success,)=owner.call{value:amount}("");
       require(success, "Transfer failed!");
     }
    

This function should be only called by the owner.

  • If you want to withdraw entire balance during emergency situation:

    function emergencyWithdrawAll() external onlyWhenStopped onlyOwner {
       (bool success,)=owner.call{value:address(this).balance}("");
       require(success,"Transfer failed!");
     }
    

this function have two modifier: onlyWhenStopped onlyOwner

Use the Emergency Stop pattern when

  • you want to have the ability to pause your contract.
  • you want to guard critical functionality against the abuse of undiscovered bugs.
  • you want to prepare your contract for potential failures.

Modifiers:

modifier onlyOwner() {
    // owner is storage variable is set during constructor
    if (msg.sender != owner) {
      revert OnlyOwner();
    }
    _;
  }
  • for onlyWhenStopped we set a state variable:

      bool public isStopped=false; 
    

then the modifier

modifier onlyWhenStopped{
    require(isStopped);
    _;
  }

Upvotes: 1

Petr Hejda
Petr Hejda

Reputation: 43581

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.

Upvotes: 20

ƛƛƛ
ƛƛƛ

Reputation: 892

Assuming your contract is ERC20, The transfer function defined in EIP 20 says:

Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The function SHOULD throw if the message caller’s account balance does not have enough tokens to spend.

Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.

function transfer(address _to, uint256 _value) public returns (bool success)

When you're calling an implementation of transfer, you're basically updating the balances of the caller and the recipient. Their balances usually are kept in a mapping/lookup table data structure.

See ConsenSys's implementation of transfer.

Upvotes: 3

Related Questions