3. Storage Factory

Importing Contracts into other Contracts | Interacting with other contracts

SimpleStorage.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract SimpleStorage {
    uint256 favNumber;

    mapping(string => uint256) public nameToFavNumber;

    struct People {
        uint256 favNum;
        string name;
    }

    People[] public people;

    function store(uint256 _favNumber) public {
        favNumber = _favNumber;
    }

    function retrieve() public view returns (uint256) {
        return favNumber;
    }

    function addPerson(string memory _name, uint256 _favNumber) public {
        people.push(People(_favNumber, _name));
        nameToFavNumber[_name] = _favNumber;
    }
}

StorageFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./SimpleStorage.sol";

contract StorageFactory {

    SimpleStorage[] public simpleStorageArray;

    function createSimpleStorageContract() public {
        SimpleStorage simpleStorage = new SimpleStorage();
        simpleStorageArray.push(simpleStorage);
    }

    function sfStore(uint256 _simpleStorageIndex, uint256 _simpleStorageNumber) public {
        // Incase simpleStorageArray had type address[]
        // SimpleStorage simpleStorage = SimpleStorage(simpleStorageArray[_simpleStorageIndex]);

        // SimpleStorage simpleStorage = simpleStorageArray[_simpleStorageIndex];
        // simpleStorage.store(_simpleStorageNumber);

        simpleStorageArray[_simpleStorageIndex].store(_simpleStorageNumber);
    }

    function sfGet(uint256 _simpleStorageIndex) public view returns (uint256) {
        // SimpleStorage simpleStorage = simpleStorageArray[_simpleStorageIndex];
        // return simpleStorage.retrieve();

        return simpleStorageArray[_simplStorageIndex].retrieve();
    }

}

Inheritance & Overrides

SimpleStorage.sol

contract SimpleStorage {
    // ...

    function store(uint256 _favNumber) public virtual {
        favNumber = _favNumber;
    }

    // ...
}

ExtraStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./SimpleStorage.sol";

contract ExtraStorage is SimpleStorage {

    // We want store function to add 5 in every value given
    // We will override the function

    // Keywords
    // Virtual : We use with the function of parent contract we want to override
    // Override : We use with the function of child contract we want to override

    function store(uint256 _favNumber) public override {
        favNumber = _favNumber + 5;
    }

}

Last updated