Solidity Exercise - Cross Contract

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

Cross Contract

Let go into this exercise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.13;

contract CrossContract {
    /**
     * The function below is to call the price function of PriceOracle1 and PriceOracle2 contracts below and return the lower of the two prices
     */

    function getLowerPrice(
        address _priceOracle1,
        address _priceOracle2
    ) external view returns (uint256) {
        // your code here
    }
}

contract PriceOracle1 {
    uint256 private _price;

    function setPrice(uint256 newPrice) public {
        _price = newPrice;
    }

    function price() external view returns (uint256) {
        return _price;
    }
}

contract PriceOracle2 {
    uint256 private _price;

    function setPrice(uint256 newPrice) public {
        _price = newPrice;
    }

    function price() external view returns (uint256) {
        return _price;
    }
}

Problem Analysis

There are two Oracle contracts provide price service, each can set and get a price. The mission is get two prices, compare, and return the lower one.
The key is how to instantiate a contract which already deployed on blockchain.
We use contract name and address to instantiate a contract.

Coding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
contract CrossContract {
    /**
     * The function below is to call the price function of PriceOracle1 and PriceOracle2 contracts below and return the lower of the two prices
     */

    function getLowerPrice(
        address _priceOracle1,
        address _priceOracle2
    ) external view returns (uint256) {
        // your code here
        PriceOracle1 priceOracle1 = PriceOracle1(_priceOracle1);
        PriceOracle2 priceOracle2 = PriceOracle2(_priceOracle2);
        uint256 price1 = priceOracle1.price();
        uint256 price2 = priceOracle2.price();
        return price1 < price2 ? price1 : price2;
    }
}

Test

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

Ran 1 test for test/CrossContract.t.sol:CrossContractTest
[PASS] testGetLowerPrice() (gas: 74161)
Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 4.70ms (355.29µs CPU time)

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

Great, we passed 1 test cases!

Reference: Solidity Exercise - CrossContract