Solidity Exercise - Distribute Transfer

Posted by Bourne's Blog - A Full-stack & Web3 Developer on May 10, 2024

Distribute Transfer

This exercise assumes you know how to sending Ether.

This contract has some ether in it, distribute it equally among the array of addresses that is passed as argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.13;

contract Distribute {
    /*
        This exercise assumes you know how to sending Ether.
        1. This contract has some ether in it, distribute it equally among the
           array of addresses that is passed as argument.
        2. Write your code in the `distributeEther` function.
    */

    constructor() payable {}

    function distributeEther(address[] memory addresses) public {
        // your code here
    }
}

Problem Analysis

First we need to know the balance of the contract. Then, we get send amount by divide the number of all addresses. Last, we call the transfer function to send the Ether.

Coding

1
2
3
4
5
6
7
    function distributeEther(address[] memory addresses) public {
        // your code here
        uint256 amount = address(this).balance / addresses.length;
        for (uint i = 0; i < addresses.length; i++) {
            payable(addresses[i]).transfer(amount);
        }
    }

Test

1
2
3
4
5
6
7
8
9
10
11
➜  Distribute git:(main) ✗ forge test -vvv
[⠊] Compiling...
[⠒] Compiling 19 files with Solc 0.8.25
[⠑] Solc 0.8.25 finished in 587.96ms
Compiler run successful!

Ran 1 test for test/Distribute.t.sol:DistributeTest
[PASS] testDistributeEther() (gas: 147356)
Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 4.10ms (259.00µs CPU time)

Ran 1 test suite in 142.00ms (4.10ms CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)

Great, we passed the test!

Reference: Solidity Exercise - Distribute