solidity - 如何可靠地从我的合约中提取所有代币
问题描述
谁能帮我?
我创建了一个基本的合约。但是不知道提款功能。请帮助我。谢谢大家 我尝试创建一个基本功能但它不起作用
function withdraw() public {
msg.sender.transfer(address(this).balance);
}
解决方案
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.
推荐阅读
- c# - C# 中的打印预览制作问题
- ios - Firebase iOS - 未定义符号:_GULResetLogger (arm64)
- docker - docker-compose 内部 DNS 服务器 127.0.0.11 连接被拒绝
- android - 安卓工作室中的应用
- node.js - 如何使用 node.js 连接到雪花
- python - 如何使用 python 在字符串分区中使用正则表达式?
- php - 如何在没有变量的情况下使用php在url中传递值?
- css - 选择具有某种颜色的所有元素?
- angular - 带有 Apollo 的 Angular graphql
- python - 将每月数据更改为每日数据,并将值分布在该月的每一天