Open In App

Solidity Global Variables

Global variables in Solidity are predefined variables available in any function or contract. These variables reveal blockchain, contract, and transaction data. Some common global variables in Solidity:

Variable Type Description
msg.sender address The address of the account that sent the current transaction.
msg.value  uint The amount of Ether sent with the current transaction.
block.coinbase  address The address of the miner who mined the current block.
block.difficulty  uint The difficulty of the current block.
block.gaslimit  uint The maximum amount of gas that can be used in the current block.
block.number  uint The number of the current block.
block.timestamp  uint  The timestamp of the current block.
now uint An alias for block.timestamp.
tx.origin  address  The address of the account that originally created the transaction (i.e., the sender of the first transaction in the call chain).
tx.gasprice  uint The gas price (in Wei) of the current transaction.

These variables are handy for getting blockchain and transaction information but use them carefully. Authentication and authorization should not utilize tx.origin since attackers may simply fake it. Use msg.sender instead.



Below is the Solidity program to implement global variables:




// Solidity program to implement 
// global variables
pragma solidity ^0.8.0;
  
contract GlobalVariablesExample {
    
  address public owner;
  constructor() 
  {
    // set the contract owner to the address 
    // that deployed the contract
    owner = msg.sender; 
  }
    
  function getOwner() public view returns (address) 
  {
    // return the contract owner address
    return owner; 
  }
    
  function isOwner(address _address) public view returns (bool
  {
    // check if the provided address matches 
    // the contract owner
    return _address == owner; 
  }
    
  function sendEther(address payable _recipient) public payable 
  {
    // send ether to the specified recipient
    require(msg.sender == owner, 
            "Only the contract owner can send ether.");
    _recipient.transfer(msg.value); 
  }
    
  function getCurrentBlock() public view returns (uint, 
                                                  uint, address) 
  {
    // return the current block number, timestamp, 
    // and coinbase address
    return (block.number, block.timestamp, block.coinbase); 
  }
}

Explanation: This example defines the GlobalVariablesExample contract. The function Object() { [native code] } initializes the owner state variable to the contract’s deployment address using the msg.sender global variable.



The contract specifies global variable functions:

Global variables may be used in Solidity contracts to make choices and execute logic.

 


Article Tags :