Solidity Exercise - Basic Bank V2

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

Basic Bank V2

Let’s go deeper of the basic bank.

Overview the code

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

contract BasicBankV2 {
    /// used to store the balance of users
    ///     USER    =>  BALANCE
    mapping(address => uint256) public balances;

    /// @notice deposit ether into the contract
    /// @dev it should work properly when called multiple times
    function addEther() external payable {}

    /// @notice used to withdraw ether from the contract
    /// @param amount of ether to remove. Cannot execeed balance i.e users cannot withdraw more than they deposited
    function removeEther(uint256 amount) external payable {}
}

Problem Analysis

Compared to the previous version, an additional variable balances has been added to store the balance of each user.
When perform addEther/removeEther, we need to add/remove amount to/from the balance of that address.

CAUTION: Ensure to check the balance before transfer ether to another user.

Coding

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

contract BasicBankV2 {
    /// used to store the balance of users
    ///     USER    =>  BALANCE
    mapping(address => uint256) public balances;

    /// @notice deposit ether into the contract
    /// @dev it should work properly when called multiple times
    function addEther() external payable {
        balances[msg.sender] += msg.value;
    }

    /// @notice used to withdraw ether from the contract
    /// @param amount of ether to remove. Cannot execeed balance i.e users cannot withdraw more than they deposited
    function removeEther(uint256 amount) external payable {
        require(balances[msg.sender] >= amount, "cannot transfer amount greater than balance");
        payable(msg.sender).transfer(amount);
        balances[msg.sender] -= amount;
    }
}

Test

Let’s run the test command:

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

Ran 2 tests for test/BasicBankV2.t.sol:BasicBankV2Test
[PASS] testAddEther() (gas: 37569)
[PASS] testRemoveEther() (gas: 33227)
Suite result: ok. 2 passed; 0 failed; 0 skipped; finished in 5.20ms (1.34ms CPU time)

Ran 1 test suite in 146.26ms (5.20ms CPU time): 2 tests passed, 0 failed, 0 skipped (2 total tests)

Great, we passed 2 test cases!

Reference: Solidity Exercise - Basic Bank V2