Solidity Addresses
An address is the unique id of one account, written with the address type. A contract can store an address, read it back, and ask how much ether that address holds.
A contract can store an address and read it back
The wallet variable starts with one fake address. The setWallet function replaces it with a new one.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract AddressBook {
address public wallet = address(0xA11CE);
function setWallet(address newWallet) public {
wallet = newWallet;
}
}An address with nothing stored reads as the zero address
A fresh address variable holds address(0). The hasNoWallet function proves this with one comparison.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract EmptyWallet {
address public wallet;
function setWallet(address newWallet) public {
wallet = newWallet;
}
function hasNoWallet() public returns (bool) {
return wallet == address(0);
}
}An address can report its ether balance in wei
Writing .balance after an address reads its balance. The answer is a plain number counted in wei.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract BalanceReader {
function balanceOf(address wallet) public returns (uint256) {
return wallet.balance;
}
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract WalletBook {
address public savedWallet;
function setWallet(address newWallet) public {
savedWallet = newWallet;
}
function hasNoWallet() public returns (bool) {
return savedWallet == address(0);
}
function savedBalance() public returns (uint256) {
return savedWallet.balance;
}
}Key points
- Account: an account is a place that can hold ether and interact with contracts.
- Ether: ether is the money of the network, and every account balance is counted in it.
- Wei: a wei is the smallest piece of ether, and balances are counted in wei.
- Address type: a variable written as address stores one account id.
- Zero address: address(0) is the empty default value, and it names no real account.
- Balance: writing .balance after an address reads its ether balance in wei.
In this example, the contract saves one wallet address in savedWallet. The hasNoWallet function compares it with address(0), and savedBalance reads the balance of the saved address in wei.
Note
the fake addresses in these lessons, like address(0xA11CE), are made-up examples and belong to nobody.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
What does a fresh address variable hold before anything is stored in it?