Solidity

將資金從合約分散到地址

  • June 1, 2022

我有一份契約,其中包含一些資金,我想將這些資金平等地轉移到以數組形式保存的地址。例如,合約中的 3 個乙太幣意味著 1 個乙太幣流向 3 個地址數組中的每個地址。這到底是怎麼做的?

//SPDX-License-Identifier: MIT

pragma solidity 0.8.14;

contract RSVP {

   address public Host;
   address[] public rsvpAddresses;
   address[] public checkedInAddresses;

   enum Status {RSVPInProgress, RSVPCheckInOver}
   Status public status;

   constructor() {
       Host = msg.sender;  
   }

   /// Only the Host can call this function
   error OnlyHost();

   modifier onlyHost() {
       if (msg.sender != Host) {
           revert OnlyHost();
       }
       _;
   }

   function rsvp() public payable {
       require(msg.value == 1 ether, "You must pay 1 ether to RSVP");
       rsvpAddresses.push(payable(msg.sender));
   }

   function getBalance() public view onlyHost returns (uint) {
       return address(this).balance;
   }

   function eventStartCheckIn(address payable guest) public onlyHost {
       for (uint i = 0; i < rsvpAddresses.length; i++) {
           if (guest == rsvpAddresses[i])
           guest.transfer(1 ether);
           checkedInAddresses.push(guest);
       }
   }

   function checkInOver() public onlyHost {
       status = Status.RSVPCheckInOver;
   }

   function disperseRemainingFunds() public onlyHost {
       require(status == Status.RSVPCheckInOver);
       uint disbursement = (address(this).balance / checkedInAddresses.length);
       
   }

}

你可以做這樣的事情。


address[] public addressArray;

function distribute() public {
   uint256 arrayLength = addressArray.length;
   uint256 amountToPay = address(this).balance/arrayLength;
   uint256 i;
   for(i =0; i<arrayLength -1; i++ ){
       payable(addressArray[i]).transfer(amountToPay);
   }
   payable(addressArray[arrayLength-1]).transfer(address(this).balance);
}

我們轉移到循環外的最後一個地址,因為整數除法返回除法的地板函式,這意味著一些資金可能仍在合約中,但不會大於 wei 中的地址數。因此,如果您的數組中有 20 個地址,您的最後一個地址可能會收到最多 19 個額外的 wei。

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