2019-01-09 11:25:45 +00:00
|
|
|
.. index:: !mapping
|
|
|
|
.. _mapping-types:
|
|
|
|
|
|
|
|
Mapping Types
|
|
|
|
=============
|
|
|
|
|
2022-08-11 11:35:59 +00:00
|
|
|
Mapping types use the syntax ``mapping(KeyType KeyName? => ValueType ValueName?)`` and variables of
|
|
|
|
mapping type are declared using the syntax ``mapping(KeyType KeyName? => ValueType ValueName?)
|
|
|
|
VariableName``. The ``KeyType`` can be any built-in value type, ``bytes``, ``string``, or any
|
|
|
|
contract or enum type. Other user-defined or complex types, such as mappings, structs or array types
|
|
|
|
are not allowed. ``ValueType`` can be any type, including mappings, arrays and structs. ``KeyName``
|
|
|
|
and ``ValueName`` are optional (so ``mapping(KeyType => ValueType)`` works as well) and can be any
|
|
|
|
valid identifier that is not a type.
|
2019-01-09 11:25:45 +00:00
|
|
|
|
|
|
|
You can think of mappings as `hash tables <https://en.wikipedia.org/wiki/Hash_table>`_, which are virtually initialised
|
|
|
|
such that every possible key exists and is mapped to a value whose
|
2019-12-16 15:53:09 +00:00
|
|
|
byte-representation is all zeros, a type's :ref:`default value <default-value>`.
|
|
|
|
The similarity ends there, the key data is not stored in a
|
2019-01-09 11:25:45 +00:00
|
|
|
mapping, only its ``keccak256`` hash is used to look up the value.
|
|
|
|
|
|
|
|
Because of this, mappings do not have a length or a concept of a key or
|
2019-09-16 17:55:17 +00:00
|
|
|
value being set, and therefore cannot be erased without extra information
|
|
|
|
regarding the assigned keys (see :ref:`clearing-mappings`).
|
2019-01-09 11:25:45 +00:00
|
|
|
|
|
|
|
Mappings can only have a data location of ``storage`` and thus
|
|
|
|
are allowed for state variables, as storage reference types
|
|
|
|
in functions, or as parameters for library functions.
|
|
|
|
They cannot be used as parameters or return parameters
|
|
|
|
of contract functions that are publicly visible.
|
2020-06-07 16:00:52 +00:00
|
|
|
These restrictions are also true for arrays and structs that contain mappings.
|
2019-01-09 11:25:45 +00:00
|
|
|
|
2019-05-16 10:27:30 +00:00
|
|
|
You can mark state variables of mapping type as ``public`` and Solidity creates a
|
2022-08-11 11:35:59 +00:00
|
|
|
:ref:`getter <visibility-and-getters>` for you. The ``KeyType`` becomes a parameter
|
|
|
|
with name ``KeyName`` (if specified) for the getter.
|
|
|
|
If ``ValueType`` is a value type or a struct, the getter returns ``ValueType`` with
|
|
|
|
name ``ValueName`` (if specified).
|
2022-02-16 02:59:49 +00:00
|
|
|
If ``ValueType`` is an array or a mapping, the getter has one parameter for
|
|
|
|
each ``KeyType``, recursively.
|
2019-10-18 08:16:03 +00:00
|
|
|
|
|
|
|
In the example below, the ``MappingExample`` contract defines a public ``balances``
|
|
|
|
mapping, with the key type an ``address``, and a value type a ``uint``, mapping
|
|
|
|
an Ethereum address to an unsigned integer value. As ``uint`` is a value type, the getter
|
|
|
|
returns a value that matches the type, which you can see in the ``MappingUser``
|
|
|
|
contract that returns the value at the specified address.
|
2019-01-09 11:25:45 +00:00
|
|
|
|
2021-06-25 10:25:29 +00:00
|
|
|
.. code-block:: solidity
|
2019-01-09 11:25:45 +00:00
|
|
|
|
2020-05-13 15:45:58 +00:00
|
|
|
// SPDX-License-Identifier: GPL-3.0
|
2020-09-08 08:48:04 +00:00
|
|
|
pragma solidity >=0.4.0 <0.9.0;
|
2019-01-09 11:25:45 +00:00
|
|
|
|
|
|
|
contract MappingExample {
|
|
|
|
mapping(address => uint) public balances;
|
|
|
|
|
|
|
|
function update(uint newBalance) public {
|
|
|
|
balances[msg.sender] = newBalance;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
contract MappingUser {
|
|
|
|
function f() public returns (uint) {
|
|
|
|
MappingExample m = new MappingExample();
|
|
|
|
m.update(100);
|
|
|
|
return m.balances(address(this));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-16 15:53:09 +00:00
|
|
|
The example below is a simplified version of an
|
|
|
|
`ERC20 token <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol>`_.
|
2019-10-18 08:16:03 +00:00
|
|
|
``_allowances`` is an example of a mapping type inside another mapping type.
|
2022-08-11 11:35:59 +00:00
|
|
|
|
|
|
|
In the example below, the optional ``KeyName`` and ``ValueName`` are provided for the mapping.
|
|
|
|
It does not affect any contract functionality or bytecode, it only sets the ``name`` field
|
|
|
|
for the inputs and outputs in the ABI for the mapping's getter.
|
|
|
|
|
|
|
|
.. code-block:: solidity
|
|
|
|
|
|
|
|
// SPDX-License-Identifier: GPL-3.0
|
|
|
|
pragma solidity ^0.8.18;
|
|
|
|
|
|
|
|
contract MappingExampleWithNames {
|
|
|
|
mapping(address user => uint balance) public balances;
|
|
|
|
|
|
|
|
function update(uint newBalance) public {
|
|
|
|
balances[msg.sender] = newBalance;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-10-18 08:16:03 +00:00
|
|
|
The example below uses ``_allowances`` to record the amount someone else is allowed to withdraw from your account.
|
|
|
|
|
2021-06-25 10:25:29 +00:00
|
|
|
.. code-block:: solidity
|
2019-10-18 08:16:03 +00:00
|
|
|
|
2020-05-13 15:45:58 +00:00
|
|
|
// SPDX-License-Identifier: GPL-3.0
|
2020-09-08 08:48:04 +00:00
|
|
|
pragma solidity >=0.4.22 <0.9.0;
|
2019-10-18 08:16:03 +00:00
|
|
|
|
|
|
|
contract MappingExample {
|
|
|
|
|
2023-02-01 18:49:34 +00:00
|
|
|
mapping(address => uint256) private _balances;
|
|
|
|
mapping(address => mapping(address => uint256)) private _allowances;
|
2019-10-18 08:16:03 +00:00
|
|
|
|
|
|
|
event Transfer(address indexed from, address indexed to, uint256 value);
|
|
|
|
event Approval(address indexed owner, address indexed spender, uint256 value);
|
|
|
|
|
|
|
|
function allowance(address owner, address spender) public view returns (uint256) {
|
|
|
|
return _allowances[owner][spender];
|
|
|
|
}
|
|
|
|
|
|
|
|
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
|
2021-12-30 11:31:20 +00:00
|
|
|
require(_allowances[sender][msg.sender] >= amount, "ERC20: Allowance not high enough.");
|
|
|
|
_allowances[sender][msg.sender] -= amount;
|
2019-10-18 08:16:03 +00:00
|
|
|
_transfer(sender, recipient, amount);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2021-12-30 11:31:20 +00:00
|
|
|
function approve(address spender, uint256 amount) public returns (bool) {
|
2019-10-18 08:16:03 +00:00
|
|
|
require(spender != address(0), "ERC20: approve to the zero address");
|
|
|
|
|
2021-12-30 11:31:20 +00:00
|
|
|
_allowances[msg.sender][spender] = amount;
|
|
|
|
emit Approval(msg.sender, spender, amount);
|
2019-10-18 08:16:03 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
function _transfer(address sender, address recipient, uint256 amount) internal {
|
|
|
|
require(sender != address(0), "ERC20: transfer from the zero address");
|
|
|
|
require(recipient != address(0), "ERC20: transfer to the zero address");
|
2021-12-30 11:31:20 +00:00
|
|
|
require(_balances[sender] >= amount, "ERC20: Not enough funds.");
|
2019-10-18 08:16:03 +00:00
|
|
|
|
|
|
|
_balances[sender] -= amount;
|
|
|
|
_balances[recipient] += amount;
|
|
|
|
emit Transfer(sender, recipient, amount);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-11-01 14:07:08 +00:00
|
|
|
.. index:: !iterable mappings
|
|
|
|
.. _iterable-mappings:
|
2019-01-09 11:25:45 +00:00
|
|
|
|
2019-11-01 14:07:08 +00:00
|
|
|
Iterable Mappings
|
|
|
|
-----------------
|
|
|
|
|
2019-12-16 15:53:09 +00:00
|
|
|
You cannot iterate over mappings, i.e. you cannot enumerate their keys.
|
|
|
|
It is possible, though, to implement a data structure on
|
2019-11-01 14:07:08 +00:00
|
|
|
top of them and iterate over that. For example, the code below implements an
|
2022-03-24 00:15:17 +00:00
|
|
|
``IterableMapping`` library that the ``User`` contract then adds data to, and
|
2019-11-01 14:07:08 +00:00
|
|
|
the ``sum`` function iterates over to sum all the values.
|
|
|
|
|
2021-06-25 10:25:29 +00:00
|
|
|
.. code-block:: solidity
|
2021-07-14 17:32:42 +00:00
|
|
|
:force:
|
2019-11-01 14:07:08 +00:00
|
|
|
|
2020-05-13 15:45:58 +00:00
|
|
|
// SPDX-License-Identifier: GPL-3.0
|
2022-02-28 16:57:19 +00:00
|
|
|
pragma solidity ^0.8.8;
|
2019-11-01 14:07:08 +00:00
|
|
|
|
2019-12-16 15:53:09 +00:00
|
|
|
struct IndexValue { uint keyIndex; uint value; }
|
|
|
|
struct KeyFlag { uint key; bool deleted; }
|
2019-11-01 14:07:08 +00:00
|
|
|
|
2019-12-16 15:53:09 +00:00
|
|
|
struct itmap {
|
|
|
|
mapping(uint => IndexValue) data;
|
|
|
|
KeyFlag[] keys;
|
|
|
|
uint size;
|
|
|
|
}
|
2019-11-01 14:07:08 +00:00
|
|
|
|
2022-02-28 16:57:19 +00:00
|
|
|
type Iterator is uint;
|
|
|
|
|
2019-12-16 15:53:09 +00:00
|
|
|
library IterableMapping {
|
2019-11-01 14:07:08 +00:00
|
|
|
function insert(itmap storage self, uint key, uint value) internal returns (bool replaced) {
|
|
|
|
uint keyIndex = self.data[key].keyIndex;
|
|
|
|
self.data[key].value = value;
|
|
|
|
if (keyIndex > 0)
|
|
|
|
return true;
|
|
|
|
else {
|
2019-11-07 13:22:14 +00:00
|
|
|
keyIndex = self.keys.length;
|
2020-04-30 16:14:45 +00:00
|
|
|
self.keys.push();
|
2019-11-01 14:07:08 +00:00
|
|
|
self.data[key].keyIndex = keyIndex + 1;
|
|
|
|
self.keys[keyIndex].key = key;
|
|
|
|
self.size++;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function remove(itmap storage self, uint key) internal returns (bool success) {
|
|
|
|
uint keyIndex = self.data[key].keyIndex;
|
|
|
|
if (keyIndex == 0)
|
|
|
|
return false;
|
|
|
|
delete self.data[key];
|
|
|
|
self.keys[keyIndex - 1].deleted = true;
|
|
|
|
self.size --;
|
|
|
|
}
|
|
|
|
|
|
|
|
function contains(itmap storage self, uint key) internal view returns (bool) {
|
|
|
|
return self.data[key].keyIndex > 0;
|
|
|
|
}
|
|
|
|
|
2022-02-28 16:57:19 +00:00
|
|
|
function iterateStart(itmap storage self) internal view returns (Iterator) {
|
|
|
|
return iteratorSkipDeleted(self, 0);
|
2019-11-01 14:07:08 +00:00
|
|
|
}
|
|
|
|
|
2022-02-28 16:57:19 +00:00
|
|
|
function iterateValid(itmap storage self, Iterator iterator) internal view returns (bool) {
|
|
|
|
return Iterator.unwrap(iterator) < self.keys.length;
|
2019-11-01 14:07:08 +00:00
|
|
|
}
|
|
|
|
|
2022-02-28 16:57:19 +00:00
|
|
|
function iterateNext(itmap storage self, Iterator iterator) internal view returns (Iterator) {
|
|
|
|
return iteratorSkipDeleted(self, Iterator.unwrap(iterator) + 1);
|
2019-11-01 14:07:08 +00:00
|
|
|
}
|
|
|
|
|
2022-02-28 16:57:19 +00:00
|
|
|
function iterateGet(itmap storage self, Iterator iterator) internal view returns (uint key, uint value) {
|
|
|
|
uint keyIndex = Iterator.unwrap(iterator);
|
2019-11-01 14:07:08 +00:00
|
|
|
key = self.keys[keyIndex].key;
|
|
|
|
value = self.data[key].value;
|
|
|
|
}
|
2022-02-28 16:57:19 +00:00
|
|
|
|
|
|
|
function iteratorSkipDeleted(itmap storage self, uint keyIndex) private view returns (Iterator) {
|
|
|
|
while (keyIndex < self.keys.length && self.keys[keyIndex].deleted)
|
|
|
|
keyIndex++;
|
|
|
|
return Iterator.wrap(keyIndex);
|
|
|
|
}
|
2019-11-01 14:07:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// How to use it
|
|
|
|
contract User {
|
|
|
|
// Just a struct holding our data.
|
2019-12-16 15:53:09 +00:00
|
|
|
itmap data;
|
|
|
|
// Apply library functions to the data type.
|
|
|
|
using IterableMapping for itmap;
|
2019-11-01 14:07:08 +00:00
|
|
|
|
|
|
|
// Insert something
|
|
|
|
function insert(uint k, uint v) public returns (uint size) {
|
2019-12-16 15:53:09 +00:00
|
|
|
// This calls IterableMapping.insert(data, k, v)
|
|
|
|
data.insert(k, v);
|
|
|
|
// We can still access members of the struct,
|
|
|
|
// but we should take care not to mess with them.
|
2019-11-01 14:07:08 +00:00
|
|
|
return data.size;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Computes the sum of all stored data.
|
|
|
|
function sum() public view returns (uint s) {
|
2019-12-16 15:53:09 +00:00
|
|
|
for (
|
2022-02-28 16:57:19 +00:00
|
|
|
Iterator i = data.iterateStart();
|
2022-02-16 03:24:44 +00:00
|
|
|
data.iterateValid(i);
|
|
|
|
i = data.iterateNext(i)
|
2019-12-16 15:53:09 +00:00
|
|
|
) {
|
2022-02-16 03:24:44 +00:00
|
|
|
(, uint value) = data.iterateGet(i);
|
2019-11-01 14:07:08 +00:00
|
|
|
s += value;
|
|
|
|
}
|
|
|
|
}
|
2019-12-16 15:53:09 +00:00
|
|
|
}
|