0
0
BlockchainConceptBeginner · 3 min read

What is msg.sender in Solidity: Explained with Examples

msg.sender in Solidity is a special variable that holds the address of the account or contract that called the current function. It helps identify who is interacting with the smart contract at any moment.
⚙️

How It Works

Imagine you have a mailbox that only opens when the owner sends a letter. In Solidity, msg.sender is like the return address on that letter. It tells the contract who sent the message or called the function.

When someone interacts with a smart contract, either a person or another contract, msg.sender captures their address. This lets the contract know who is making the request, so it can decide what actions to allow or deny.

Think of it as a way for the contract to check the identity of the caller before doing anything important, like sending money or changing data.

💻

Example

This example shows a simple contract where only the owner can change a stored number. The contract uses msg.sender to check who is calling the function.

solidity
pragma solidity ^0.8.0;

contract OwnerOnly {
    address public owner;
    uint public number;

    constructor() {
        owner = msg.sender; // Set the deployer as owner
    }

    function setNumber(uint _number) public {
        require(msg.sender == owner, "Only owner can set number");
        number = _number;
    }

    function getNumber() public view returns (uint) {
        return number;
    }
}
🎯

When to Use

You use msg.sender whenever you need to know who is calling your contract. This is important for security and control.

  • To restrict access to certain functions, like only allowing the owner to change settings.
  • To track who sent a transaction or interacted with your contract.
  • To build contracts that behave differently depending on the caller, such as voting or permission systems.

In real life, it’s like checking someone's ID before letting them enter a club or use a service.

Key Points

  • msg.sender is the address of the caller of the current function.
  • It can be an external user or another contract.
  • It is used for access control and identifying who interacts with the contract.
  • Always check msg.sender to secure sensitive functions.

Key Takeaways

msg.sender holds the address of the caller interacting with the contract.
Use msg.sender to control who can execute certain functions.
It helps secure contracts by verifying the identity of the caller.
Both users and contracts can be msg.sender.
Always check msg.sender before performing sensitive actions.