Global variables in solidity

Global variables in solidity

Like every other programming language, solidity also have built-in global variables which are really useful when you are building a smart contract.

1. msg

  • msg.sender:-
    This variable returns the address of the user or contract who is currently connecting with the contract. The value of msg.sender can change for every external call.
    function getAddress() public view returns(address)
    {
      return msg.sender;
    }
    
    This code will give the result. Here i deployed the contract that's why msg.sender is returning my address.

Screenshot from 2022-04-01 12-59-05.png

  • msg.value:-
    Returns the amount of wei(smallest unit of ether, 1ETH = 10^18wei) sent to the smart contract.
    Suppose you sent 1ETH to this smart contract
    uint public money;
    function pay() external payable
    {
      money = msg.value;
    }
    
    The value of the variable money will be

Screenshot from 2022-04-01 16-45-34.png

2. block

  • block.timestamp:-
    It returns the current block timestamp in unix epoch.
    function get() public view returns(uint){
          return block.timestamp;
      }
    
    The time is in unix epoch,

Screenshot from 2022-04-22 19-58-15.png After converting it to human readable time it becomes Friday, April 22, 2022 7:54:56 PM.

  • block.number:-
    Returns the current block number

3. tx

  • tx.gasprice:-
    Returns the gas price of transaction in wei.

  • tx.origin:-
    Returns the address of sender of the transaction.
    Note:- One thing you should understand about tx.origin is that it will always return the address of external account while msg.sender will return the address of contract or external account.