Back to homepage

Solidity fundamentals: Global variables (msg, this & block)

Published

In Solidity, there are certain global variables that are available inside all functions, even if they are not sent as function parameters. Let's review some of them:

msg.sender

This variable refers to the address of the person (or smart contract) who called the current function. Here's an example of using msg.sender and updating a mapping:

mapping (address => string) addressUsernames;

function setMyNumber(string memory _name) public {
  // Update our `addressUsernames` mapping to store the name under `msg.sender`
  addressUsernames[msg.sender] = _name;
}

function getUsername() public view returns (string) {
  // Retrieve the user name using the caller's address
  return addressUsernames[msg.sender];
}

In Solidity, all function executions need to start with an external caller so there will always be a msg.sender.

msg.value

The msg.value global variable contains the amount of ETH that was sent in the transaction. For example if we have built a lottery game and in which users have to pay 0.1ETH per ticket to play, we validate it that like this:

pragma solidity ^0.8.4;


contract MyContract {

  uint256 ticketPrice = 0.1 ether;

  function playLottery(uint256 _number) public payable {
    // validate value sent
    require(msg.value >= ticketPrice, "Minimum value is 0.1 ETH!");
  }
}

this

The this global variable in Solidity refers to the current smart contract and the returned value can be typed to an address. For example if we have a contract that receives ETH from users, we could retrieve the contract's balance like this:

pragma solidity ^0.8.4;


contract MyContract {

  function getContractBalance() public view returns (uint256) {

    return address(this).balance;
  }
}

block.timestamp

The block.timestamp global variable returns the current block timestamp as seconds since unix epoch.

block.difficulty

The block.difficulty global variable returns current block difficulty.

TAGS

If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Buy Me A Coffee