Calling functions of a member variable of a deployed smart contract using web3

53 views Asked by At

I have a smart contract deployed (Setup.sol), and it imports another smart contract "Model.sol" which has some functions that I need to call. Now, I only have contract address of the deployment of Setup.sol, and therefore am confused with how to call functions of its member variable model.

For reference, here is the code of Setup.sol :


pragma solidity 0.8.19;

import "./Model.sol";

contract Setup {

    Model public model;

    constructor() payable {
        model = new Model();
    }

    function isSolved() public view returns (bool) {
        return magic.solved();
    }
}

I am getting the setup_contract using setup_contract = w3.eth.contract(address = address, abi = setup_abi) but, can't find a way to use the public member variable model from the setup_contract.

Thanks!

1

There are 1 answers

0
norym On BEST ANSWER

Consider the following scenario.

Your Setup contract:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;

import "./Model.sol";

contract Setup {

    Model public model;

    constructor() {
        model = new Model();
    }

    function isSolved() public pure returns (bool) {
        return false;
    }
}

Your model contract:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;

contract Model {
    function isSolved() public pure returns (bool) {
        return true;
    }
}

As far as I understand, you would like to call functions of "its member variable" Model contract referenced in your Setup contract.

Firstly, Model public model in Setup contract stores the address of the Model contract. So instantiate Setup contract and call public member variable (reading state).

address = '...'
abi = '...'
setup_instance = w3.eth.contract(address=address, abi=abi)

model_contract_address = setup_instance.functions.model().call()

Now, having the address of Model contract, instantiate Model contract and call any function you like.

address = model_contract_address
abi = '...'
model_instance = w3.eth.contract(address=address, abi=abi)

model_instance.functions.isSolved().call()