sun*_*hul 2 blockchain ethereum solidity smartcontracts binance-smart-chain
我有一个 erc20 代币,在另一个合约中我想创建一个代币交换功能。所以很容易,发送一个 usdc 代币并以 1:1 的比例交换我的 erc20 代币。问题是如何批准使用我的 erc20 代币。我尝试了几次但找不到方法。
interface IERC20 {...}
contract AnotherContract {
function approve(address _spender, uint256 _amount) public returns(bool) {
return IERC20(MyToken).approve(_spender, _amount);
}
Run Code Online (Sandbox Code Playgroud)
我部署了另一个合同,当我从中调用批准功能时。所以当我将“_spender”设置为这个合约地址时。结果很奇怪。所以这个合约既是所有者又是消费者。我认为用户应该是所有者,而这个合约应该是消费者。但是函数是从链上调用的。msg.sender 将是该合约地址本身。
我不明白并且很困惑。有人知道或者有一些资源吗?谢谢。
当您AnotherContract执行approve()in 中的函数时MyToken,msg.senderinMyToken不是AnotherContract原始交易发送者。
这有效地批准了AnotherContract花费的代币_spender。
除非MyToken有办法委托批准(例如,使用已弃用的tx.origin而不是msg.sender,这会引入安全缺陷),否则用户将必须手动执行批准,而不是通过外部合同。
许多 ERC-20 实现都使用这种方法来实现安全目的。例如,为了防止诈骗者说服用户执行其恶意功能,因为用户会认为他们正在获得空投。
// function name suggests that the caller is going to receive an airdrop
function claimAirdrop() external {
/*
* fortunately, this won't work
* and the tx sender can't approve the scammer to spend their tokens this way
*/
USDTcontract.approve(scammer, 1000000);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5016 次 |
| 最近记录: |