Issue in accessing public variable from another contract in solidity

24 views Asked by At

Why the get function in Fetch contract not able to fetch the value of storeData variable which is imported from the SimpleStorage contract. Both the contracts are present in separate files.

file name- importCheck.sol

code-

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

// import "contracts/Hello.sol";

import * as newSymbol from "contracts/Hello.sol";

contract Fetch {
    newSymbol.SimpleStorage public demo = new newSymbol.SimpleStorage();

    function getStoreData() public view returns(uint) {
        return demo.get();
    }
}

file name- Hello.sol

code-

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

contract SimpleStorage {
    uint public storeData;

    function set(uint x) public {
        storeData = x;
    }

    function get() public view returns (uint){
        return storeData;
    }
    
}

I have deployed both the contracts in Remix VM as well as in Sepolia test net but still the storeData variable is not returning the value assigned in the SimpleStorage contract.

1

There are 1 answers

1
Petr Hejda On
newSymbol.SimpleStorage public demo = new newSymbol.SimpleStorage();

This line from your original code deploys a new instance of the SimpleStorage contract, and stores it to a new address (this address is available in your demo variable).


If you want to access an existing contract, you can create a contract or interface type pointer without the new keyword, passing it the existing contract address.

newSymbol.SimpleStorage public demo = newSymbol.SimpleStorage(address(0x123));