Solidity Msg Sender
Msg.sender is the address that called the current function. A contract can read it to learn who called.
A contract can record its last caller
Each call to record stores the caller. The stored address is whoever called most recently.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CallerLog {
address public lastCaller;
function record() public {
lastCaller = msg.sender;
}
}
A mapping keeps one count per caller
The caller address works as a mapping key. Each sender gets a separate count.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CallerCounts {
mapping(address => uint256) public callsFrom;
function record() public {
callsFrom[msg.sender] += 1;
}
}
A function can return its caller
Msg.sender is a value the function can return. The answer is always the current caller.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract WhoCalled {
function whoCalled() public view returns (address) {
return msg.sender;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CallerRegistry {
address public lastCaller;
mapping(address => uint256) public callsFrom;
function record() public {
lastCaller = msg.sender;
callsFrom[msg.sender] += 1;
}
}
Key points
- Msg.sender: the address of the account or contract that made the call.
- Address: the 20-byte id of an account or a contract.
- Use msg.sender to record who made a call.
- A mapping keyed by msg.sender keeps a separate record per caller.
- Msg.sender changes with each call, so read it inside the function.
In this example, record first stores msg.sender as the last caller. It then adds one to the count stored under that same address. Two different callers build up two separate counts. The last caller is always the sender of the most recent call.
Note
msg.sender can be another contract, not only a person.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
Two different addresses call the same function. What is msg.sender on the second call?