首页 > 解决方案 > 如何可靠地从我的合约中提取所有代币

问题描述

谁能帮我?

我创建了一个基本的合约。但是不知道提款功能。请帮助我。谢谢大家 我尝试创建一个基本功能但它不起作用

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

标签: soliditysmartcontractserc20

解决方案


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.


推荐阅读