【问题标题】:ehtereum smart contract approve spender from another contract以太坊智能合约批准另一个合约的支出者
【发布时间】:2021-07-26 18:15:48
【问题描述】:

我有一个 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);
}

我部署了另一个合同,当我从中调用批准功能时。因此,当我将“_spender”设置为此合约地址时。结果很奇怪。所以这个合同既是所有者又是支出者。我认为用户应该是所有者,而这个合同应该是支出者。但是从链上调用函数。 msg.sender 将是这个合约地址。

我不明白,也很困惑。有人知道或有一些资源吗?谢谢。

【问题讨论】:

    标签: blockchain ethereum solidity smartcontracts binance-smart-chain


    【解决方案1】:

    当您的AnotherContract 执行MyToken 中的approve() 函数时,MyToken 中的msg.senderAnotherContract - 不是原始交易发送者。

    这有效地批准了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);
    }
    

    【讨论】:

    • 谢谢~。老实说,我现在不太了解智能合约的逻辑。我解决了我的问题,例如有一次在合同之外请求批准并请求交易以花费用户令牌(在津贴中)。
    • @Seong 你是怎么做到的?能给个示例代码吗?
    • @seongcheolryu 你是怎么做到的?能给个示例代码吗?
    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2017-04-06
    • 2019-07-27
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多