Solidity

在 ERC-20 代幣中實現拆分支付

  • July 12, 2022

我是這個話題的新手。我正在嘗試實現一種方法來在代幣合約本身內拆分付款。我知道有一個單獨的付款拆分契約,但我想嘗試在代幣契約中實現它。

我寫過這樣的方法。你能告訴我:

  1. 以這種方式付款是否安全?
  2. 是否可以以任何其他方式實施(但在代幣合約本身內部)?
   function splitPayment(address from, address firstReceiver, address secondReceiver, uint256 amount) public {
       require(from != address(0), "ERC20: transfer from the zero address");
       require(firstReceiver != address(0), "ERC20: transfer to the zero address");
       require(secondReceiver != address(0), "ERC20: transfer to the zero address");

       uint256 fromBalance = _balances[from];
       require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");

       unchecked {
           _balances[from] = fromBalance - amount;
       }

       _balances[firstReceiver] += amount * 70 / 100;
       _balances[secondReceiver] += amount * 30 / 100;

       emit SplittedTransfer(from, firstReceiver, secondReceiver, amount);
   }

對的,這是可能的。這樣分期付款就更好了,這裡不用太擔心

function splitTransfer(address firstReceiver ,address secondReceiver,  uint256 amount) public virtual returns (bool) {
       address owner = _msgSender();
       _transfer(owner, firstReceiver, amount* 70 / 100);
       _transfer(owner, secondReceiver, amount* 30 / 100);
       return true;
   }

這種拆分代幣的方式看起來還可以,但是你需要確保代幣不能被任何人轉移。您在這裡有兩個選擇:

  1. 代幣只能由其所有者拆分
  2. 代幣只能由其所有者或已獲得津貼的人分割

選項 1 如下所示:

require(from == msg.sender, "ERC20: transfer of foreign assets");

選項 2 如下所示:

require(from == msg.sender || _allowances[from][msg.sender] >= amount, "ERC20: exceeds allowance");

如果您使用選項 2,您還必須確保更新_allowances並發出Approval事件。

我認為最好發出 2 個Transfer事件而不是創建一個新事件,因為Transfer事件是標準化的。

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