0

I learned how to call the function of another contract in solidity. However, I can not find any approach to access to the state variables as follow attempt, so how to do it in solidity ^0.8.17?

contract A {
    uint public x = 3;
}



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

import "./A.sol";

contract B {
    A public contractA ;

    function getAcontractState() public{
        contractA = new A();
        uint y = contractA.x; // error is here.
    }
}   

2 Answers 2

2
interface IContractA {
 uint public x;
}

contract B {

    function getContractAState() public returns (uint256){
        IContractA contractA = IContractA(contractAAddress);
        uint256 y = contractA.x()
        return y;
    }
}

Create an interface for the ContractA and interact with it through the interface.

0

Public fields in contracts become externally accessible by their getters, which are auto generated by Solidity with the same name.

Example:

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

contract A {
    uint public x = 3;
}

contract B {
    A public contractA ;

    function getAcontractState() public returns (uint256){
        contractA = new A();
        uint256 y = contractA.x(); // error was here.
        return y;
    }
}

Hope this solves your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.