Search code examples
mappingethereumsoliditysmartcontractsether

What is the use of msg.sender in solidity?


In this codpiece, I am finding it hard to figure out what is msg.sender is and how it works internally.

What I am understanding is, we have a mapping favoriteNumber, and the key is an address and the value is a uint.

What is the meaning of comment - "Update our favoriteNumber mapping to store _myNumber under msg.sender, I am understanding that we are updating favoriteNumber, but what does it mean that under msg.sender. What is the role of this method, how it's working?

    mapping (address => uint) favoriteNumber;

function setMyNumber(uint _myNumber) public {
  // Update our `favoriteNumber` mapping to store `_myNumber` under `msg.sender`
  favoriteNumber[msg.sender] = _myNumber;
  // ^ The syntax for storing data in a mapping is just like with arrays
}

function whatIsMyNumber() public view returns (uint) {
  // Retrieve the value stored in the sender's address
  // Will be `0` if the sender hasn't called `setMyNumber` yet
  return favoriteNumber[msg.sender];
}

Solution

  • Every smart contract invocation has a caller address. Each EVM (Ethereum Virtual Machine that executes the code) knows which account carries out each action. In Solidity, you can access the calling account by referencing msg.sender

    So when you call a function of solidity contract, your contract already gets the information of your account, so your account is the msg.sender

    favoriteNumber is a mapping. think it like a javascript object. It maps the account addresses to their favourite number.

     0x9C6520Dd9F8d0af1DA494C37b64D4Cea9A65243C -> 10 
    

    So when you call setMyNumber(_myNumber), you are passing your favourite number. so this number will be stored in favoriteNumber mapping like this:

     yourAccountAdress -> yourFavouriteNumber
    

    So when you call whatIsMyNumber function, since EVM already gets your account number, checks in the mappings and returns you your favourite number.