0
0
BlockchainConceptBeginner · 3 min read

What is msg.value in Solidity: Explained with Examples

msg.value in Solidity is a special variable that holds the amount of Ether (in wei) sent with a transaction to a contract. It lets the contract know how much money was transferred during the call.
⚙️

How It Works

Imagine you are handing money to a friend along with a note. In Solidity, when you send Ether to a smart contract, msg.value is like the amount of money you handed over. It tells the contract exactly how much Ether came with the transaction.

This value is measured in wei, the smallest unit of Ether, similar to how cents relate to dollars. The contract can then use msg.value to decide what to do next, like recording a payment or giving a service.

💻

Example

This example shows a simple contract that accepts Ether and stores the amount sent using msg.value.

solidity
pragma solidity ^0.8.0;

contract PayableExample {
    uint public lastAmount;

    // Function to receive Ether and store the amount sent
    function pay() public payable {
        lastAmount = msg.value;
    }

    // Function to get the contract's balance
    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
}
🎯

When to Use

You use msg.value whenever your contract needs to know how much Ether was sent with a transaction. This is common in:

  • Payable functions that accept payments or deposits.
  • Smart contracts for crowdfunding or token sales where users send Ether to buy tokens.
  • Any contract logic that depends on receiving funds, like auctions or escrow services.

Without msg.value, the contract cannot tell how much money was sent, so it cannot react properly to payments.

Key Points

  • msg.value is always in wei, the smallest Ether unit.
  • It only has a value when the function is marked payable.
  • It helps contracts handle incoming Ether safely and correctly.
  • It is part of the global msg object that holds transaction info.

Key Takeaways

msg.value holds the amount of Ether sent with a transaction in wei.
Use msg.value inside payable functions to handle payments.
It enables contracts to react to incoming funds like deposits or purchases.
Always remember msg.value is zero if no Ether is sent.
It is part of the global msg object containing transaction details.