Track 4 · Solidity foundations · lesson 5
msg.sender and msg.value
9 min
Track 4 · Solidity foundations · lesson 5
9 min
A contract has no users, no sessions and no login. The only thing it knows
about who is talking to it is msg.sender.
That single value is the entire basis of identity, ownership and permission in every contract ever written.
msg.sender is the address that made this call. Not the person who started
the transaction — the immediate caller.
If Alice calls contract A, and A calls contract B, then inside B msg.sender
is A, not Alice. That distinction is the whole reason tx.origin is
dangerous, and it is the mechanism behind a phishing attack you will run in
track 7.
It just records the wrong thing. Nothing is broken syntactically — the logic is wrong, and only the tests reveal it. This is what most real bugs look like.
msg.value is how much ETH came with the call, in wei.
A function can only receive ETH if it is marked payable. Send ETH to a
non-payable function and the transaction reverts — a deliberate guard against
funds getting stuck in contracts that were never written to handle them.
function donate() public payable {
donations[msg.sender] += msg.value;
}
Predict
block.timestamp — seconds since 1970. Loosely policed, and a validator
can nudge it. Never use it as a source of randomness.block.number — the current height.address(this) — the contract's own address.tx.origin — the account that started the whole transaction chain.
Almost always the wrong choice. Use msg.sender.Check