Learning Objectives – after this chapter you will be able to:
  • Use the msg, block and tx global variables.
  • Explain the difference between msg.sender and tx.origin.
  • Use Ether and time units and built-in cryptographic functions.
  • Recognise deprecated globals (now, block.difficulty) and unsafe uses.
What are Global Variables?

Global (special) variables and functions always exist in the global namespace. They give information about the current call (msg), the current block (block) and the transaction (tx), and provide utility functions. You do not declare them – you simply use them.

Global Variable Chart
Sr.No.Global VariableDescription
1msg.sender (address)Address of the account or contract that made the current call.
2msg.value (uint)Amount of wei sent with the call (only in payable functions).
3msg.data (bytes calldata)Complete call data.
4msg.sig (bytes4)First four bytes of the call data – the function selector.
5block.timestamp (uint)Current block’s timestamp in seconds since the Unix epoch.
6block.number (uint)Current block number.
7block.coinbase (address payable)Address of the current block’s proposer (fee recipient).
8block.gaslimit (uint)Current block’s gas limit.
9block.basefee (uint)Current block’s base fee (EIP-1559).
10block.chainid (uint)ID of the current chain (1 = Ethereum Mainnet).
11block.prevrandao (uint)Randomness value from the beacon chain (since the move to Proof-of-Stake). Replaces block.difficulty, which is now a deprecated alias.
12blockhash(uint blockNumber) returns (bytes32)Hash of a given block – works only for the 256 most recent blocks, excluding the current one; otherwise returns zero.
13gasleft() returns (uint256)Remaining gas in the current call.
14tx.origin (address)The externally owned account that started the whole transaction (full call chain).
15tx.gasprice (uint)Gas price of the transaction.
16address(this).balanceEther balance of the current contract, in wei.
Removed / deprecated: now was removed in Solidity 0.7.0 – use block.timestamp. block.difficulty is deprecated after Ethereum’s move to Proof-of-Stake – use block.prevrandao. Since 0.8.0, msg.sender and tx.origin are plain address; use payable(msg.sender) to send Ether.
msg.sender vs tx.origin
Alice (EOA)starts the transaction
Contract Amsg.sender = Alice
tx.origin = Alice
Contract Bmsg.sender = Contract A
tx.origin = Alice

Never use tx.origin for authorisation. If Alice is tricked into calling a malicious contract, that contract can call your contract and tx.origin will still be Alice. Use msg.sender.

Units and Built-in Functions
GroupExamples
Ether units1 wei, 1 gwei (109 wei), 1 ether (1018 wei)
Time units1 seconds, 1 minutes, 1 hours, 1 days, 1 weeks
Hashing / cryptographykeccak256(bytes), sha256(bytes), ripemd160(bytes), ecrecover(hash, v, r, s)
ABI encodingabi.encode(...), abi.encodePacked(...), abi.decode(...), abi.encodeWithSignature(...)
Type informationtype(uint8).max, type(MyContract).name, type(IERC20).interfaceId
Error handlingrequire, revert, assert (Chapter 21)
Example : Using Global Variables
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract GlobalsDemo {
    address public owner;
    uint public deployedAt;
    uint public constant LOCK_TIME = 1 days;   // time unit

    constructor() {
        owner = msg.sender;                     // who deployed the contract
        deployedAt = block.timestamp;           // when it was deployed
    }

    function deposit() external payable {
        require(msg.value >= 0.01 ether, "Send at least 0.01 ether");
    }

    function info() external view returns (address caller, uint blockNo, uint chainId, uint balance) {
        return (msg.sender, block.number, block.chainid, address(this).balance);
    }

    function isUnlocked() external view returns (bool) {
        return block.timestamp >= deployedAt + LOCK_TIME;
    }

    function hashOf(string calldata text) external pure returns (bytes32) {
        return keccak256(abi.encodePacked(text));
    }
}
Not truly random: block.timestamp, block.prevrandao and block hashes are visible to (and partly influenced by) block producers, so they must not be used for lotteries or games where money depends on randomness. Use a verifiable randomness service (e.g. a VRF oracle) or a commit–reveal scheme (see Project 2).
Key Takeaways
  • msg describes the current call, block the current block, tx the whole transaction.
  • Use msg.sender (not tx.origin) for access control; use block.timestamp (not now).
  • Block values are not a safe source of randomness.
Download | Print      E-Notes

The PDF E-Notes are the earlier printable version of this chapter. The notes on this page are the latest, revised version.

Question / Answer (15 questions)

Answer : Pre-defined variables and functions that are always available, giving information about the current call (msg), block (block) and transaction (tx), plus utility functions such as keccak256 and gasleft().

Answer : The address of the account or contract that made the current call. It changes at each step of a call chain.

Answer : msg.sender is the immediate caller of the current function; tx.origin is the externally owned account that started the entire transaction. If Alice calls contract A, which calls contract B, then inside B msg.sender is A while tx.origin is Alice.

Answer : A malicious contract that the owner is tricked into calling can call your contract while tx.origin is still the owner, bypassing the check (a phishing-style attack). Use msg.sender instead.

Answer : msg.value is the amount of wei sent with the call. It can be non-zero only in payable functions; non-payable functions reject Ether.

Answer : The current block’s timestamp in seconds since the Unix epoch (1 January 1970).

Answer : now was an alias for block.timestamp and was removed in Solidity 0.7.0; code must use block.timestamp.

Answer : block.prevrandao, after Ethereum moved from Proof-of-Work to Proof-of-Stake (EIP-4399). Under PoS there is no mining difficulty, and the DIFFICULTY opcode now returns the beacon chain randomness value.

Answer : Only for the 256 most recent blocks, excluding the current block. For other block numbers it returns zero.

Answer : The first four bytes of the call data, i.e. the function selector that identifies which function is being called.

Answer : With address(this).balance, which returns the balance in wei.

Answer : Ether units: wei, gwei and ether (1 ether = 10^18 wei). Time units: seconds, minutes, hours, days and weeks.

Answer : They are known to everyone once the block is produced and can be partly influenced by block producers, so players or validators could predict or manipulate outcomes. Verifiable randomness (VRF) or commit-reveal schemes are safer.

Answer : It returns the amount of gas remaining in the current call. It can be used to measure gas usage or to stop long operations before running out of gas.

Answer : No. Since 0.8.0 msg.sender is a plain address; to send Ether to it you convert it with payable(msg.sender).
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Alice calls contract A, which calls contract B. Inside B, msg.sender is:

Show Answer

Correct Answer : C. Contract A
msg.sender is the immediate caller.

Q2. Which global variable should be used for access control?

Show Answer

Correct Answer : A. msg.sender
tx.origin is unsafe for authorisation.

Q3. Which keyword was removed in Solidity 0.7.0?

Show Answer

Correct Answer : B. now
Use block.timestamp instead of now.

Q4. 1 ether equals:

Show Answer

Correct Answer : D. 10^18 wei
1 ether = 10^18 wei.

Q5. Which value replaced block.difficulty after the move to Proof-of-Stake?

Show Answer

Correct Answer : C. block.prevrandao
EIP-4399 introduced PREVRANDAO.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Solidity Team. (n.d.). Units and Globally Available Variables. Solidity Documentation. https://docs.soliditylang.org/en/latest/units-and-global-variables.html
  2. Solidity Team. (n.d.). Security Considerations. Solidity Documentation. https://docs.soliditylang.org/en/latest/security-considerations.html
  3. Ethereum Improvement Proposals. (2021). EIP-4399: Supplant DIFFICULTY opcode with PREVRANDAO. https://eips.ethereum.org/EIPS/eip-4399
  4. ethereum.org. (n.d.). Transactions. Ethereum Developer Documentation. https://ethereum.org/en/developers/docs/transactions/
  5. Chainlink. (n.d.). Chainlink VRF (Verifiable Random Function) documentation. https://docs.chain.link/vrf
  6. Modi, R. (2018). Solidity Programming Essentials: A beginner’s guide to build smart contracts for Ethereum and blockchain. Packt Publishing. ISBN 978-1-78883-138-3.