Solidity Nested Mappings
A nested mapping is a mapping whose values are mappings. It looks up a value with two keys, one after the other.
Write and read a pair
The outer key is the owner, and the inner key is the spender. Two brackets write one amount for that pair.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract AllowanceBook {
mapping(address => mapping(address => uint256)) public allowances;
function setAllowance(address owner, address spender, uint256 amount) public {
allowances[owner][spender] = amount;
}
}
Pairs are independent
The same owner can have different amounts for different spenders. Changing one pair leaves the other pair untouched.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract AllowanceBook {
mapping(address => mapping(address => uint256)) public allowances;
function setAllowance(address owner, address spender, uint256 amount) public {
allowances[owner][spender] = amount;
}
}
A missing pair reads 0
Writing one pair does not create values for other pairs. A pair that was never written reads 0.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract AllowanceBook {
mapping(address => mapping(address => uint256)) public allowances;
function setAllowance(address owner, address spender, uint256 amount) public {
allowances[owner][spender] = amount;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract AllowanceBook {
mapping(address => mapping(address => uint256)) public allowances;
function setAllowance(address owner, address spender, uint256 amount) public {
allowances[owner][spender] = amount;
}
function getAllowance(address owner, address spender) public view returns (uint256) {
return allowances[owner][spender];
}
}
Key points
- Two keys: the first key leads to an inner mapping, and the second key leads to the value.
- Allowance: an amount one address lets another address use, stored here as a plain number.
- Write: allowances[owner][spender] = 50 stores 50 for that pair of addresses.
- Read: allowances[owner][spender] gives back the amount stored for that pair.
- Missing pair: a pair that was never written reads 0.
- Independent pairs: each pair of keys holds its own value.
In this example, allowances maps an owner address to an inner mapping, and the inner mapping maps a spender address to an amount. The setAllowance function writes an amount for one owner and spender pair. The getAllowance function reads one pair back with both keys. Changing the Ana and Bea pair leaves the Cam and Bea pair at 30, and a pair never written reads 0.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
In allowances[owner][spender], what does the pair of keys identify?