These are special variables in smart contracts that tell you who sent a message and how much money they sent. They help your contract know who is interacting with it and with what value.
0
0
msg.value and msg.sender in Blockchain / Solidity
Introduction
When you want to know which user is calling your smart contract function.
When you want to check how much cryptocurrency was sent with a transaction.
When you want to make sure only the owner or a specific user can perform an action.
When you want to accept payments or deposits in your contract.
When you want to log or react to the sender's address or the amount sent.
Syntax
Blockchain / Solidity
msg.sender msg.value
msg.sender is the address of the caller (the person or contract sending the message).
msg.value is the amount of cryptocurrency (in wei) sent with the message.
Examples
Store the sender's address and the sent amount in variables.
Blockchain / Solidity
address sender = msg.sender; uint amount = msg.value;
Check that the sender sent exactly 1 ether with the transaction.
Blockchain / Solidity
require(msg.value == 1 ether, "Send exactly 1 ether");
A function that accepts payment and logs who paid and how much.
Blockchain / Solidity
function pay() public payable {
emit Paid(msg.sender, msg.value);
}Sample Program
This contract has a function pay that anyone can call to send ether. It checks that some ether was sent and then emits an event showing who sent it and how much.
Blockchain / Solidity
pragma solidity ^0.8.0; contract SimplePay { event Paid(address sender, uint amount); function pay() public payable { require(msg.value > 0, "Send some ether"); emit Paid(msg.sender, msg.value); } }
OutputSuccess
Important Notes
msg.sender is always the immediate caller of the function, which can be a user or another contract.
msg.value is zero if no ether is sent with the call.
These variables are only available inside payable functions or functions called by transactions.
Summary
msg.sender tells you who called the contract.
msg.value tells you how much ether was sent.
Use them to control access and handle payments in your smart contracts.