Search code examples
solidityweb3jsmetamaskwallet-connect

useContractRead overrides changes msg.sender


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.


Solution

  • 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.