ERC20代币转移到智能合约

ERC20 token transfer to smart contract

您好,我编写了一个简单的智能合约,用于将 erc20 令牌从用户转移到智能合约,以及从智能合约转移到用户。我在调用 transferFrom 函数之前批准它,但交易失败。我试过只调用 approve 而不是调用 transferFrom 它有效。我正在 rinkeby 测试网上进行测试。

// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

}

contract transferToContract {
    address public _WETH = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984;
    IERC20 public WETH = IERC20(_WETH);

    function transferToC (uint amount) public
    {
        WETH.approve(msg.sender,amount);
        WETH.transferFrom(msg.sender,address(this),amount);
    }
    
    function transferFromC(uint amount) public{
        WETH.approve(address(this),amount);
        WETH.transferFrom(address(this),msg.sender,amount);
    }
    
    function getbal() public view returns(uint){
        return WETH.balanceOf(msg.sender);
    }
    
    
}

我正在测试注入 web3 的 remix。我得到的错误是

Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
execution reverted: Uni::transferFrom: transfer amount exceeds spender allowance { "originalError": { "code": 3, "data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003c556e693a3a7472616e7366657246726f6d3a207472616e7366657220616d6f756e742065786365656473207370656e64657220616c6c6f77616e636500000000", "message": "execution reverted: Uni::transferFrom: transfer amount exceeds spender allowance" } }

此外,我在 rinkeby 测试网上的测试钱包中有令牌,我正在使用注入的 remix web3 进行部署。

WETH.approve(msg.sender,amount);

此行批准用户使用您合约的代币。反之则不然。

如果你想批准合约来操纵用户的代币,用户需要直接在WETH合约上执行approve(yourContractAddress, amount)(而不是通过你的合约)。


我在另一个答案中介绍了类似的主题。 TLDR 部分也与您的问题相关 -

我希望我的合约接受来自外部账户的代币,该账户的代币很少(可以是任何代币,但基于 ERC20)。所以要直接调用 approve 函数我需要创建一个令牌合约的实例,那么我如何使用 web3 创建实例?

任何代码片段都会有所帮助,或者如果您可以将 link 分享到任何相同的文档也会有所帮助。