3

Let's suppose this smartcontract:

contract Test1 {
   string private i_am_private;
   string public i_am_public;
   ...
}

Solidity's compiler is automatically generating a getter function for public fields. So we can easily read value from another contract or from a DAPP.

But everything is stored on blockchain and everything is public. So it might have a way to read private fields too... We can do that manually by browsing a blockchain explorer for example. But is there a simple way to do that from a DAPP or from another smart contract ?

Thanks

1 Answer 1

2

You can't read the data from another contract, but you can read it outside the blockchain.

Having a private field means that only that contract can read the data on-chain. If you want to read the data off-chain you basically either have to analyze incoming transactions or consult your node client whether it provides some support for such functionality - there may be some sort of "contract current state" for example which may show the data directly. I'm not an expert with clients so don't know for sure what would be the easiest way.

3
  • From the offchain, you can. For example with web3.js, you can use web3.eth.getStorageAt. Commented Jan 13, 2021 at 9:22
  • Thanks for the comment. Edited a bit, but I'm not familiar enough with getStorageAt that I'd feel comfortable about writing about it. Feel free to add another answer with that specific info Commented Jan 13, 2021 at 9:28
  • Why don't you give it a try and see? I've only started using it recently, and it is quite handy. For example, await web3.eth.getStorageAt(contractAddress, 0) reads the first 256-bit slot in the contract. In the code above, I'm not sure that it would read the actual contents of the string, but possibly its length. There's a whole section in the official documentation about storage slots. It gets more complicated for arrays and mappings, and in the latter case, it is indeed not possible to get mapped values using this method (i.e., you'd need to analyze past transactions, as you describe). Commented Jan 13, 2021 at 9:45

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.