0

I am using wagmi's useContractRead to fetch data from my solidity contract, now problem is that in that contract I use msg.sender to access the data about sender. My solidity code looks like this:

    function getInfo() public view returns (bool, uint8, address) {
        return (
            data[msg.sender].ts != 0,
            data[msg.sender].info,
            msg.sender
        );
    }

and by default useContractRead is returning [false, 0, '0x0000000000000000000000000000000000000000'], bear in mind if i call this exact same function with useContract I need to pass signer, otherwise it throws an error (using metamask).

My useContractRead looks like this

  const { isConnected, address } = useAccount();

  useContractRead({
    abi: currentEnvContract.abi,
    address: currentEnvContract.address,
    functionName: 'getInfo',
    enabled: isConnected,
    // overrides: { from: '0x765d5A82bba93F44fa3514d6dce9f7351dF1b7fA' },
    onSuccess: (data) => {
      console.log(data);
    },
  });

as you see I have overrides.from commented, and that address does not belong to me, it is random address I found on goerli etherscan. and if I uncomment it the contract will return [false, 0, '0x765d5A82bba93F44fa3514d6dce9f7351dF1b7fA']

why does this happen? I should not be able to use this address. and if this is wrong, is there way to send my current connected address as msg.from to my solidity contract.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Ratokl
  • 11
  • 1
  • 1
  • 2

1 Answers1

0

There's a difference between a read-write transaction and read-only call.

A transaction needs to be signed by a private key of the sender, so that the miner/validator can deduct gas fees from the sender address - and as a result of that, msg.sender always reflects this address. However, a call is executed only on the node that you're connected to, is not propagated to the rest of the network, and doesn't deduct any fees.

Since call doesn't deduct any fees, you can specify any (or the default zero) address as the caller.

There can be no harm done on the contract by passing another caller address, because a call is read-only and cannot store any changes.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • Thanks for the info, but thing that confuses me is, if i have private variables in my solidity contract that should only be accessed by someone who initialized for example private mapping and i only someone want to access that mapping's info if their info is saved there, i would not be able to do that with read-only call? – Ratokl Dec 23 '22 at 16:03
  • @Ratokl They are non-readable by other contracts. But they are still readable using offchain methods - for example by reading the value of the storage slot where the private variable is stored: https://web3js.readthedocs.io/en/v1.8.1/web3-eth.html#getstorageat – Petr Hejda Dec 23 '22 at 20:06