Solidity

是否可以在其他契約的單個功能中同時使用批准和轉移功能?

  • December 22, 2020

我意識到你需要批准你要發送給契約的代幣數量。為此,您應該首先在代幣合約中使用approve函式,然後在其他合約中呼叫trasferfrom函式(例如購買函式)

但是有沒有辦法在同一個購買功能中使用批准功能?當我使用批准功能時,出現錯誤。我檢查了 msg.sender 的值……這是呼叫該函式的使用者,但我仍然得到錯誤。在我想從購買合約中呼叫購買功能之前,我不想每次都使用令牌合約中的批准功能。程式碼如下:(這裡不貼額外程式碼)

pragma solidity >=0.6.0 <0.8.0;
contract ERC20{
function approve(address spender, uint256 amount) public returns (bool) {        
   require(msg.sender != address(0), "ERC20: approve from the zero address");
   require(spender != address(0), "ERC20: approve to the zero address");
   _allowances[msg.sender][spender] = amount;
   emit Approval(msg.sender, spender, amount);
   return true;
}

function approveWithSender(address sender, address spender, uint256 amount) external returns (bool) {        
   require(sender != address(0), "ERC20: approve from the zero address");
   require(spender != address(0), "ERC20: approve to the zero address");
   require(sender == msg.sender,"You cannot approve other users");
   _allowances[sender][spender] = amount;
   emit Approval(sender, spender, amount);
   return true;
}
}

contract Buy{

ERC20 tokenAddress;
address contractAddress = address(this);


constructor (address _tokenAddress) public{
   tokenAddress = ERC20(_tokenAddress);
}

function buy(uint amount) public{
   
   //tokenAddress.approveWithSender(msg.sender, contractAddress, amount);
   //tokenAddress.approve(contractAddress, amount);
   require(amount > 0, "You need to sell at least some tokens");
   uint256 allowance = tokenAddress.allowance(msg.sender, address(this));
   require(allowance >= amount, "Check the token allowance");
   tokenAddress.transferFrom(msg.sender, contractAddress, amount);
}
}

如果使用approve() 函式,我會收到revert 錯誤,即使msg.sender 是呼叫該函式的使用者?

在使用approveWithSender()的情況下,我得到“你不能批准其他使用者”錯誤在令牌契約中被拒絕。

這是EIP-20兼容令牌的缺點。

備選方案:

  • EIP-777一種向後兼容 EIP-20 的令牌規範。
  • EIP 2612一種在頂級 EIP-20 上添加權限的方法,允許兼容的令牌單筆交易傳輸。DAIUNI有早期實現。

引用自:https://ethereum.stackexchange.com/questions/91362