Solidity - 转账金额超过消费者津贴

Solidity - transfer amount exceeds spender allowance

代码看起来正确,在转移前批准令牌,但失败并出现错误:“转移金额超过支出者津贴” 发件人帐户的令牌余额超过要求。

有什么想法吗? 合约:https://rinkeby.etherscan.io/address/0x2a855c479b14443489963eef90ad449ecdf40cf5#writeContract

pragma solidity ^0.7.0;  


interface IERC20 {
   function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
   function approve(address spender, uint256 amount) external returns (bool); 
   function transfer(address recipient, uint256 amount) external returns (bool);
} 
 
contract FundTokenContract { 
    address public owner;   
     
    constructor(){ 
        owner = msg.sender;
    }   
    
    modifier OnlyOwner() {
        require(msg.sender == owner, "Only owner can call this function.");
        _;
    } 
    
     function fundToken(address tokenAddress, uint amount ) external {  
        require(amount > 0);  
        IERC20(tokenAddress).approve(address(this), amount); 
        IERC20(tokenAddress).transferFrom(msg.sender ,address(this), amount);  
    }  
      
      
    function withdrawToken(address _tokenAddress, address  _recipient, uint _amount) public  OnlyOwner returns (bool){  
        IERC20(_tokenAddress).transfer(_recipient, _amount);
        return true;
    }  
}

当你的合约执行tokenAddress函数approve()时,approve()函数中的msg.sender你的合约(不是发起交易的用户)。

这有效地批准“您的合约”(第一个参数 address(this))花费“您的合约”(msg.sender)资金。

然后它试图transferFrom()用户地址,但没有得到批准。


如果你想让你的合约花费属于另一个用户的代币,他们需要从他们的地址直接执行approve(<yourContract>, <amount>)(而不是通过合约)。

注意:请参阅 中的 TLDR,它显示了此要求的用处。