Utilities
This document is better viewed at https://docs.openzeppelin.com/contracts/api/utils |
Miscellaneous contracts and libraries containing utility functions you can use to improve security, work with new data types, or safely use low-level primitives.
The Address
, Arrays
, Base64
and Strings
libraries provide more operations related to these native data types, while SafeCast
adds ways to safely convert between the different signed and unsigned numeric types.
Multicall
provides a function to batch together multiple calls in a single external call.
For new data types:
-
Counters
: a simple way to get a counter that can only be incremented, decremented or reset. Very useful for ID generation, counting contract activity, among others. -
EnumerableMap
: like Solidity’smapping
type, but with key-value enumeration: this will let you know how many entries a mapping has, and iterate over them (which is not possible withmapping
). -
EnumerableSet
: likeEnumerableMap
, but for sets. Can be used to store privileged accounts, issued IDs, etc.
Because Solidity does not support generic types, As of v3.0, |
Finally, Create2
contains all necessary utilities to safely use the CREATE2
EVM opcode, without having to deal with low-level assembly.
Math
Math
import "@openzeppelin/contracts/utils/math/Math.sol";
Standard math utilities missing in the Solidity language.
SignedMath
import "@openzeppelin/contracts/utils/math/SignedMath.sol";
Standard signed math utilities missing in the Solidity language.
SafeCast
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
Wrappers over Solidity’s uintXX/intXX casting operators with added overflow checks.
Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
easily result in undesired exploitation or bugs, since developers usually
assume that overflows raise errors. SafeCast
restores this intuition by
reverting the transaction when such an operation overflows.
Using this library instead of the unchecked operations eliminates an entire class of bugs, so it’s recommended to use it always.
Can be combined with SafeMath
and SignedSafeMath
to extend it to smaller types, by performing
all math on uint256
and int256
and then downcasting.
toUint224(uint256 value) → uint224
internal
Returns the downcasted uint224 from uint256, reverting on overflow (when the input is greater than largest uint224).
Counterpart to Solidity’s uint224
operator.
Requirements:
-
input must fit into 224 bits
toUint128(uint256 value) → uint128
internal
Returns the downcasted uint128 from uint256, reverting on overflow (when the input is greater than largest uint128).
Counterpart to Solidity’s uint128
operator.
Requirements:
-
input must fit into 128 bits
toUint96(uint256 value) → uint96
internal
Returns the downcasted uint96 from uint256, reverting on overflow (when the input is greater than largest uint96).
Counterpart to Solidity’s uint96
operator.
Requirements:
-
input must fit into 96 bits
toUint64(uint256 value) → uint64
internal
Returns the downcasted uint64 from uint256, reverting on overflow (when the input is greater than largest uint64).
Counterpart to Solidity’s uint64
operator.
Requirements:
-
input must fit into 64 bits
toUint32(uint256 value) → uint32
internal
Returns the downcasted uint32 from uint256, reverting on overflow (when the input is greater than largest uint32).
Counterpart to Solidity’s uint32
operator.
Requirements:
-
input must fit into 32 bits
toUint16(uint256 value) → uint16
internal
Returns the downcasted uint16 from uint256, reverting on overflow (when the input is greater than largest uint16).
Counterpart to Solidity’s uint16
operator.
Requirements:
-
input must fit into 16 bits
toUint8(uint256 value) → uint8
internal
Returns the downcasted uint8 from uint256, reverting on overflow (when the input is greater than largest uint8).
Counterpart to Solidity’s uint8
operator.
Requirements:
-
input must fit into 8 bits.
toUint256(int256 value) → uint256
internal
Converts a signed int256 into an unsigned uint256.
Requirements:
-
input must be greater than or equal to 0.
toInt128(int256 value) → int128
internal
Returns the downcasted int128 from int256, reverting on overflow (when the input is less than smallest int128 or greater than largest int128).
Counterpart to Solidity’s int128
operator.
Requirements:
-
input must fit into 128 bits
Available since v3.1.
toInt64(int256 value) → int64
internal
Returns the downcasted int64 from int256, reverting on overflow (when the input is less than smallest int64 or greater than largest int64).
Counterpart to Solidity’s int64
operator.
Requirements:
-
input must fit into 64 bits
Available since v3.1.
toInt32(int256 value) → int32
internal
Returns the downcasted int32 from int256, reverting on overflow (when the input is less than smallest int32 or greater than largest int32).
Counterpart to Solidity’s int32
operator.
Requirements:
-
input must fit into 32 bits
Available since v3.1.
toInt16(int256 value) → int16
internal
Returns the downcasted int16 from int256, reverting on overflow (when the input is less than smallest int16 or greater than largest int16).
Counterpart to Solidity’s int16
operator.
Requirements:
-
input must fit into 16 bits
Available since v3.1.
SafeMath
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
Wrappers over Solidity’s arithmetic operations.
SafeMath is generally not needed starting with Solidity 0.8, since the compiler
now has built in overflow checking.
|
tryAdd(uint256 a, uint256 b) → bool, uint256
internal
Returns the addition of two unsigned integers, with an overflow flag.
Available since v3.4.
trySub(uint256 a, uint256 b) → bool, uint256
internal
Returns the subtraction of two unsigned integers, with an overflow flag.
Available since v3.4.
tryMul(uint256 a, uint256 b) → bool, uint256
internal
Returns the multiplication of two unsigned integers, with an overflow flag.
Available since v3.4.
tryDiv(uint256 a, uint256 b) → bool, uint256
internal
Returns the division of two unsigned integers, with a division by zero flag.
Available since v3.4.
tryMod(uint256 a, uint256 b) → bool, uint256
internal
Returns the remainder of dividing two unsigned integers, with a division by zero flag.
Available since v3.4.
add(uint256 a, uint256 b) → uint256
internal
Returns the addition of two unsigned integers, reverting on overflow.
Counterpart to Solidity’s +
operator.
Requirements:
-
Addition cannot overflow.
sub(uint256 a, uint256 b) → uint256
internal
Returns the subtraction of two unsigned integers, reverting on overflow (when the result is negative).
Counterpart to Solidity’s -
operator.
Requirements:
-
Subtraction cannot overflow.
mul(uint256 a, uint256 b) → uint256
internal
Returns the multiplication of two unsigned integers, reverting on overflow.
Counterpart to Solidity’s *
operator.
Requirements:
-
Multiplication cannot overflow.
div(uint256 a, uint256 b) → uint256
internal
Returns the integer division of two unsigned integers, reverting on division by zero. The result is rounded towards zero.
Counterpart to Solidity’s /
operator.
Requirements:
-
The divisor cannot be zero.
mod(uint256 a, uint256 b) → uint256
internal
Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), reverting when dividing by zero.
Counterpart to Solidity’s %
operator. This function uses a revert
opcode (which leaves remaining gas untouched) while Solidity uses an
invalid opcode to revert (consuming all remaining gas).
Requirements:
-
The divisor cannot be zero.
sub(uint256 a, uint256 b, string errorMessage) → uint256
internal
Returns the subtraction of two unsigned integers, reverting with custom message on overflow (when the result is negative).
This function is deprecated because it requires allocating memory for the error
message unnecessarily. For custom revert reasons use trySub .
|
Counterpart to Solidity’s -
operator.
Requirements:
-
Subtraction cannot overflow.
div(uint256 a, uint256 b, string errorMessage) → uint256
internal
Returns the integer division of two unsigned integers, reverting with custom message on division by zero. The result is rounded towards zero.
Counterpart to Solidity’s /
operator. Note: this function uses a
revert
opcode (which leaves remaining gas untouched) while Solidity
uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
-
The divisor cannot be zero.
mod(uint256 a, uint256 b, string errorMessage) → uint256
internal
Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), reverting with custom message when dividing by zero.
This function is deprecated because it requires allocating memory for the error
message unnecessarily. For custom revert reasons use tryMod .
|
Counterpart to Solidity’s %
operator. This function uses a revert
opcode (which leaves remaining gas untouched) while Solidity uses an
invalid opcode to revert (consuming all remaining gas).
Requirements:
-
The divisor cannot be zero.
SignedSafeMath
import "@openzeppelin/contracts/utils/math/SignedSafeMath.sol";
Wrappers over Solidity’s arithmetic operations.
SignedSafeMath is no longer needed starting with Solidity 0.8. The compiler
now has built in overflow checking.
|
mul(int256 a, int256 b) → int256
internal
Returns the multiplication of two signed integers, reverting on overflow.
Counterpart to Solidity’s *
operator.
Requirements:
-
Multiplication cannot overflow.
div(int256 a, int256 b) → int256
internal
Returns the integer division of two signed integers. Reverts on division by zero. The result is rounded towards zero.
Counterpart to Solidity’s /
operator.
Requirements:
-
The divisor cannot be zero.
Cryptography
ECDSA
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
These functions can be used to verify that a message was signed by the holder of the private keys of a given address.
tryRecover(bytes32 hash, bytes signature) → address, enum ECDSA.RecoverError
internal
Returns the address that signed a hashed message (hash
) with
signature
or error string. This address can then be used for verification purposes.
The ecrecover
EVM opcode allows for malleable (non-unique) signatures:
this function rejects them by requiring the s
value to be in the lower
half order, and the v
value to be either 27 or 28.
hash must be the result of a hash operation for the
verification to be secure: it is possible to craft signatures that
recover to arbitrary addresses for non-hashed data. A safe way to ensure
this is by receiving a hash of the original message (which may otherwise
be too long), and then calling toEthSignedMessageHash on it.
|
Available since v4.3.
recover(bytes32 hash, bytes signature) → address
internal
Returns the address that signed a hashed message (hash
) with
signature
. This address can then be used for verification purposes.
The ecrecover
EVM opcode allows for malleable (non-unique) signatures:
this function rejects them by requiring the s
value to be in the lower
half order, and the v
value to be either 27 or 28.
hash must be the result of a hash operation for the
verification to be secure: it is possible to craft signatures that
recover to arbitrary addresses for non-hashed data. A safe way to ensure
this is by receiving a hash of the original message (which may otherwise
be too long), and then calling toEthSignedMessageHash on it.
|
tryRecover(bytes32 hash, bytes32 r, bytes32 vs) → address, enum ECDSA.RecoverError
internal
Overload of ECDSA.tryRecover
that receives the r
and vs
short-signature fields separately.
Available since v4.3.
recover(bytes32 hash, bytes32 r, bytes32 vs) → address
internal
Overload of ECDSA.recover
that receives the r and `vs
short-signature fields separately.
Available since v4.2.
tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) → address, enum ECDSA.RecoverError
internal
Overload of ECDSA.tryRecover
that receives the v
,
r
and s
signature fields separately.
Available since v4.3.
recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) → address
internal
Overload of ECDSA.recover
that receives the v
,
r
and s
signature fields separately.
/
toEthSignedMessageHash(bytes32 hash) → bytes32
internal
Returns an Ethereum Signed Message, created from a hash
. This
produces hash corresponding to the one signed with the
eth_sign
JSON-RPC method as part of EIP-191.
See recover
.
/
toEthSignedMessageHash(bytes s) → bytes32
internal
Returns an Ethereum Signed Message, created from s
. This
produces hash corresponding to the one signed with the
eth_sign
JSON-RPC method as part of EIP-191.
See recover
.
/
toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) → bytes32
internal
Returns an Ethereum Signed Typed Data, created from a
domainSeparator
and a structHash
. This produces hash corresponding
to the one signed with the
eth_signTypedData
JSON-RPC method as part of EIP-712.
See recover
.
/
SignatureChecker
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
Signature verification helper that can be used instead of ECDSA.recover
to seamlessly support both ECDSA
signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
Argent and Gnosis Safe.
Available since v4.1.
isValidSignatureNow(address signer, bytes32 hash, bytes signature) → bool
internal
Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
signature is validated against that smart contract using ERC1271, otherwise it’s validated using ECDSA.recover
.
Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus change through time. It could return true at block N and false at block N+1 (or the opposite). |
MerkleProof
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
These functions deal with verification of Merkle Trees proofs.
The proofs can be generated using the JavaScript library merkletreejs. Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
See test/utils/cryptography/MerkleProof.test.js
for some examples.
You should avoid using leaf values that are 64 bytes long prior to hashing, or use a hash function other than keccak256 for hashing leaves. This is because the concatenation of a sorted pair of internal nodes in the merkle tree could be reinterpreted as a leaf value. |
verify(bytes32[] proof, bytes32 root, bytes32 leaf) → bool
internal
Returns true if a leaf
can be proved to be a part of a Merkle tree
defined by root
. For this, a proof
must be provided, containing
sibling hashes on the branch from the leaf to the root of the tree. Each
pair of leaves and each pair of pre-images are assumed to be sorted.
processProof(bytes32[] proof, bytes32 leaf) → bytes32
internal
Returns the rebuilt hash obtained by traversing a Merkle tree up
from leaf
using proof
. A proof
is valid if and only if the rebuilt
hash matches the root of the tree. When processing the proof, the pairs
of leafs & pre-images are assumed to be sorted.
Available since v4.4.
EIP712
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
EIP 712 is a standard for hashing and signing of typed structured data.
The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
they need in their contracts using a combination of abi.encode
and keccak256
.
This contract implements the EIP 712 domain separator (_domainSeparatorV4
) that is used as part of the encoding
scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
(_hashTypedDataV4
).
The implementation of the domain separator was designed to be as efficient as possible while still properly updating the chain id to protect against replay attacks on an eventual fork of the chain.
This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
eth_signTypedDataV4 in MetaMask.
|
Available since v3.4.
constructor(string name, string version)
internal
Initializes the domain separator and parameter caches.
The meaning of name
and version
is specified in
EIP 712:
-
name
: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. -
version
: the current major version of the signing domain.
These parameters cannot be changed except through a smart contract upgrade. |
_hashTypedDataV4(bytes32 structHash) → bytes32
internal
Given an already hashed struct, this function returns the hash of the fully encoded EIP712 message for this domain.
This hash can be used together with ECDSA.recover
to obtain the signer of a message. For example:
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
keccak256("Mail(address to,string contents)"),
mailTo,
keccak256(bytes(mailContents))
)));
address signer = ECDSA.recover(digest, signature);
Escrow
ConditionalEscrow
import "@openzeppelin/contracts/utils/escrow/ConditionalEscrow.sol";
Base abstract escrow to only allow withdrawal if a condition is met.
Intended usage: See Escrow
. Same usage guidelines apply here.
Escrow
import "@openzeppelin/contracts/utils/escrow/Escrow.sol";
Base escrow contract, holds funds designated for a payee until they withdraw them.
Intended usage: This contract (and derived escrow contracts) should be a
standalone contract, that only interacts with the contract that instantiated
it. That way, it is guaranteed that all Ether will be handled according to
the Escrow
rules, and there is no need to check for payable functions or
transfers in the inheritance tree. The contract that uses the escrow as its
payment method should be its owner, and provide public methods redirecting
to the escrow’s deposit and withdraw.
withdraw(address payable payee)
public
Withdraw accumulated balance for a payee, forwarding all gas to the recipient.
Forwarding all gas opens the door to reentrancy vulnerabilities.
Make sure you trust the recipient, or are either following the
checks-effects-interactions pattern or using ReentrancyGuard .
|
RefundEscrow
import "@openzeppelin/contracts/utils/escrow/RefundEscrow.sol";
Escrow that holds funds for a beneficiary, deposited from multiple
parties.
Intended usage: See Escrow
. Same usage guidelines apply here.
The owner account (that is, the contract that instantiates this
contract) may deposit, close the deposit period, and allow for either
withdrawal by the beneficiary, or refunds to the depositors. All interactions
with RefundEscrow
will be made through the owner contract.
Introspection
This set of interfaces and contracts deal with type introspection of contracts, that is, examining which functions can be called on them. This is usually referred to as a contract’s interface.
Ethereum contracts have no native concept of an interface, so applications must usually simply trust they are not making an incorrect call. For trusted setups this is a non-issue, but often unknown and untrusted third-party addresses need to be interacted with. There may even not be any direct calls to them! (e.g. ERC20
tokens may be sent to a contract that lacks a way to transfer them out of it, locking them forever). In these cases, a contract declaring its interface can be very helpful in preventing errors.
There are two main ways to approach this.
-
Locally, where a contract implements
IERC165
and declares an interface, and a second one queries it directly viaERC165Checker
. -
Globally, where a global and unique registry (
IERC1820Registry
) is used to register implementers of a certain interface (IERC1820Implementer
). It is then the registry that is queried, which allows for more complex setups, like contracts implementing interfaces for externally-owned accounts.
Note that, in all cases, accounts simply declare their interfaces, but they are not required to actually implement them. This mechanism can therefore be used to both prevent errors and allow for complex interactions (see ERC777
), but it must not be relied on for security.
IERC165
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
Interface of the ERC165 standard, as defined in the EIP.
Implementers can declare support of contract interfaces, which can then be
queried by others (ERC165Checker
).
For an implementation, see ERC165
.
supportsInterface(bytes4 interfaceId) → bool
external
Returns true if this contract implements the interface defined by
interfaceId
. See the corresponding
EIP section
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
ERC165
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
Implementation of the IERC165
interface.
Contracts that want to implement ERC165 should inherit from this contract and override supportsInterface
to check
for the additional interface id that will be supported. For example:
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
}
Alternatively, ERC165Storage
provides an easier to use but more expensive implementation.
ERC165Storage
import "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol";
Storage based implementation of the IERC165
interface.
Contracts may inherit from this and call _registerInterface
to declare
their support of an interface.
_registerInterface(bytes4 interfaceId)
internal
Registers the contract as an implementer of the interface defined by
interfaceId
. Support of the actual ERC165 interface is automatic and
registering its interface id is not required.
Requirements:
-
interfaceId
cannot be the ERC165 invalid interface (0xffffffff
).
ERC165Checker
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
Library used to query support of an interface declared via IERC165
.
Note that these functions return the actual result of the query: they do not
revert
if an interface is not supported. It is up to the caller to decide
what to do in these cases.
supportsERC165(address account) → bool
internal
Returns true if account
supports the IERC165
interface,
supportsInterface(address account, bytes4 interfaceId) → bool
internal
Returns true if account
supports the interface defined by
interfaceId
. Support for IERC165
itself is queried automatically.
getSupportedInterfaces(address account, bytes4[] interfaceIds) → bool[]
internal
Returns a boolean array where each value corresponds to the interfaces passed in and whether they’re supported or not. This allows you to batch check interfaces for a contract where your expectation is that some interfaces may not be supported.
Available since v3.4.
IERC1820Registry
import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol";
Interface of the global ERC1820 Registry, as defined in the EIP. Accounts may register implementers for interfaces in this registry, as well as query support.
Implementers may be shared by multiple accounts, and can also implement more than a single interface for each account. Contracts can implement interfaces for themselves, but externally-owned accounts (EOA) must delegate this to a contract.
IERC165
interfaces can also be queried via the registry.
For an in-depth explanation and source code analysis, see the EIP text.
setManager(address account, address newManager)
external
Sets newManager
as the manager for account
. A manager of an
account is able to set interface implementers for it.
By default, each account is its own manager. Passing a value of 0x0
in
newManager
will reset the manager to this initial state.
Emits a ManagerChanged
event.
Requirements:
-
the caller must be the current manager for
account
.
setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer)
external
Sets the implementer
contract as account
's implementer for
interfaceHash
.
account
being the zero address is an alias for the caller’s address.
The zero address can also be used in implementer
to remove an old one.
See interfaceHash
to learn how these are created.
Emits an InterfaceImplementerSet
event.
Requirements:
-
the caller must be the current manager for
account
. -
interfaceHash
must not be anIERC165
interface id (i.e. it must not end in 28 zeroes). -
implementer
must implementIERC1820Implementer
and return true when queried for support, unlessimplementer
is the caller. SeeIERC1820Implementer.canImplementInterfaceForAddress
.
getInterfaceImplementer(address account, bytes32 _interfaceHash) → address
external
Returns the implementer of interfaceHash
for account
. If no such
implementer is registered, returns the zero address.
If interfaceHash
is an IERC165
interface id (i.e. it ends with 28
zeroes), account
will be queried for support of it.
account
being the zero address is an alias for the caller’s address.
interfaceHash(string interfaceName) → bytes32
external
Returns the interface hash for an interfaceName
, as defined in the
corresponding
section of the EIP.
IERC1820Implementer
import "@openzeppelin/contracts/utils/introspection/IERC1820Implementer.sol";
Interface for an ERC1820 implementer, as defined in the
EIP.
Used by contracts that will be registered as implementers in the
IERC1820Registry
.
ERC1820Implementer
import "@openzeppelin/contracts/utils/introspection/ERC1820Implementer.sol";
Implementation of the IERC1820Implementer
interface.
Contracts may inherit from this and call _registerInterfaceForAddress
to
declare their willingness to be implementers.
IERC1820Registry.setInterfaceImplementer
should then be called for the
registration to be complete.
Data Structures
BitMaps
import "@openzeppelin/contracts/utils/structs/BitMaps.sol";
Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. Largelly inspired by Uniswap’s merkle-distributor.
get(struct BitMaps.BitMap bitmap, uint256 index) → bool
internal
Returns whether the bit at index
is set.
EnumerableMap
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
Library for managing an enumerable variant of Solidity’s
mapping
type.
Maps have the following properties:
-
Entries are added, removed, and checked for existence in constant time (O(1)).
-
Entries are enumerated in O(n). No guarantees are made on the ordering.
contract Example {
// Add the library methods
using EnumerableMap for EnumerableMap.UintToAddressMap;
// Declare a set state variable
EnumerableMap.UintToAddressMap private myMap;
}
The following map types are supported:
-
uint256 → address
(UintToAddressMap
) since v3.0.0 -
address → uint256
(AddressToUintMap
) since v4.6.0 -
bytes32 → bytes32
(Bytes32ToBytes32
) since v4.6.0
set(struct EnumerableMap.Bytes32ToBytes32Map map, bytes32 key, bytes32 value) → bool
internal
Adds a key-value pair to a map, or updates the value for an existing key. O(1).
Returns true if the key was added to the map, that is if it was not already present.
remove(struct EnumerableMap.Bytes32ToBytes32Map map, bytes32 key) → bool
internal
Removes a key-value pair from a map. O(1).
Returns true if the key was removed from the map, that is if it was present.
contains(struct EnumerableMap.Bytes32ToBytes32Map map, bytes32 key) → bool
internal
Returns true if the key is in the map. O(1).
length(struct EnumerableMap.Bytes32ToBytes32Map map) → uint256
internal
Returns the number of key-value pairs in the map. O(1).
at(struct EnumerableMap.Bytes32ToBytes32Map map, uint256 index) → bytes32, bytes32
internal
Returns the key-value pair stored at position index
in the map. O(1).
Note that there are no guarantees on the ordering of entries inside the array, and it may change when more entries are added or removed.
Requirements:
-
index
must be strictly less thanlength
.
tryGet(struct EnumerableMap.Bytes32ToBytes32Map map, bytes32 key) → bool, bytes32
internal
Tries to returns the value associated with key
. O(1).
Does not revert if key
is not in the map.
get(struct EnumerableMap.Bytes32ToBytes32Map map, bytes32 key) → bytes32
internal
Returns the value associated with key
. O(1).
Requirements:
-
key
must be in the map.
get(struct EnumerableMap.Bytes32ToBytes32Map map, bytes32 key, string errorMessage) → bytes32
internal
Same as {_get}, with a custom error message when key
is not in the map.
This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {_tryGet}. |
set(struct EnumerableMap.UintToAddressMap map, uint256 key, address value) → bool
internal
Adds a key-value pair to a map, or updates the value for an existing key. O(1).
Returns true if the key was added to the map, that is if it was not already present.
remove(struct EnumerableMap.UintToAddressMap map, uint256 key) → bool
internal
Removes a value from a set. O(1).
Returns true if the key was removed from the map, that is if it was present.
contains(struct EnumerableMap.UintToAddressMap map, uint256 key) → bool
internal
Returns true if the key is in the map. O(1).
length(struct EnumerableMap.UintToAddressMap map) → uint256
internal
Returns the number of elements in the map. O(1).
at(struct EnumerableMap.UintToAddressMap map, uint256 index) → uint256, address
internal
Returns the element stored at position index
in the set. O(1).
Note that there are no guarantees on the ordering of values inside the
array, and it may change when more values are added or removed.
Requirements:
-
index
must be strictly less thanlength
.
tryGet(struct EnumerableMap.UintToAddressMap map, uint256 key) → bool, address
internal
Tries to returns the value associated with key
. O(1).
Does not revert if key
is not in the map.
Available since v3.4.
get(struct EnumerableMap.UintToAddressMap map, uint256 key) → address
internal
Returns the value associated with key
. O(1).
Requirements:
-
key
must be in the map.
get(struct EnumerableMap.UintToAddressMap map, uint256 key, string errorMessage) → address
internal
Same as get
, with a custom error message when key
is not in the map.
This function is deprecated because it requires allocating memory for the error
message unnecessarily. For custom revert reasons use tryGet .
|
set(struct EnumerableMap.AddressToUintMap map, address key, uint256 value) → bool
internal
Adds a key-value pair to a map, or updates the value for an existing key. O(1).
Returns true if the key was added to the map, that is if it was not already present.
remove(struct EnumerableMap.AddressToUintMap map, address key) → bool
internal
Removes a value from a set. O(1).
Returns true if the key was removed from the map, that is if it was present.
contains(struct EnumerableMap.AddressToUintMap map, address key) → bool
internal
Returns true if the key is in the map. O(1).
length(struct EnumerableMap.AddressToUintMap map) → uint256
internal
Returns the number of elements in the map. O(1).
at(struct EnumerableMap.AddressToUintMap map, uint256 index) → address, uint256
internal
Returns the element stored at position index
in the set. O(1).
Note that there are no guarantees on the ordering of values inside the
array, and it may change when more values are added or removed.
Requirements:
-
index
must be strictly less thanlength
.
tryGet(struct EnumerableMap.AddressToUintMap map, address key) → bool, uint256
internal
Tries to returns the value associated with key
. O(1).
Does not revert if key
is not in the map.
Available since v3.4.
get(struct EnumerableMap.AddressToUintMap map, address key) → uint256
internal
Returns the value associated with key
. O(1).
Requirements:
-
key
must be in the map.
get(struct EnumerableMap.AddressToUintMap map, address key, string errorMessage) → uint256
internal
Same as get
, with a custom error message when key
is not in the map.
This function is deprecated because it requires allocating memory for the error
message unnecessarily. For custom revert reasons use tryGet .
|
EnumerableSet
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
Library for managing sets of primitive types.
Sets have the following properties:
-
Elements are added, removed, and checked for existence in constant time (O(1)).
-
Elements are enumerated in O(n). No guarantees are made on the ordering.
contract Example {
// Add the library methods
using EnumerableSet for EnumerableSet.AddressSet;
// Declare a set state variable
EnumerableSet.AddressSet private mySet;
}
As of v3.3.0, sets of type bytes32
(Bytes32Set
), address
(AddressSet
)
and uint256
(UintSet
) are supported.
add(struct EnumerableSet.Bytes32Set set, bytes32 value) → bool
internal
Add a value to a set. O(1).
Returns true if the value was added to the set, that is if it was not already present.
remove(struct EnumerableSet.Bytes32Set set, bytes32 value) → bool
internal
Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present.
contains(struct EnumerableSet.Bytes32Set set, bytes32 value) → bool
internal
Returns true if the value is in the set. O(1).
length(struct EnumerableSet.Bytes32Set set) → uint256
internal
Returns the number of values in the set. O(1).
at(struct EnumerableSet.Bytes32Set set, uint256 index) → bytes32
internal
Returns the value stored at position index
in the set. O(1).
Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed.
Requirements:
-
index
must be strictly less thanlength
.
values(struct EnumerableSet.Bytes32Set set) → bytes32[]
internal
Return the entire set in an array
This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. |
add(struct EnumerableSet.AddressSet set, address value) → bool
internal
Add a value to a set. O(1).
Returns true if the value was added to the set, that is if it was not already present.
remove(struct EnumerableSet.AddressSet set, address value) → bool
internal
Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present.
contains(struct EnumerableSet.AddressSet set, address value) → bool
internal
Returns true if the value is in the set. O(1).
length(struct EnumerableSet.AddressSet set) → uint256
internal
Returns the number of values in the set. O(1).
at(struct EnumerableSet.AddressSet set, uint256 index) → address
internal
Returns the value stored at position index
in the set. O(1).
Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed.
Requirements:
-
index
must be strictly less thanlength
.
values(struct EnumerableSet.AddressSet set) → address[]
internal
Return the entire set in an array
This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. |
add(struct EnumerableSet.UintSet set, uint256 value) → bool
internal
Add a value to a set. O(1).
Returns true if the value was added to the set, that is if it was not already present.
remove(struct EnumerableSet.UintSet set, uint256 value) → bool
internal
Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present.
contains(struct EnumerableSet.UintSet set, uint256 value) → bool
internal
Returns true if the value is in the set. O(1).
length(struct EnumerableSet.UintSet set) → uint256
internal
Returns the number of values on the set. O(1).
at(struct EnumerableSet.UintSet set, uint256 index) → uint256
internal
Returns the value stored at position index
in the set. O(1).
Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed.
Requirements:
-
index
must be strictly less thanlength
.
values(struct EnumerableSet.UintSet set) → uint256[]
internal
Return the entire set in an array
This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. |
DoubleEndedQueue
import "@openzeppelin/contracts/utils/structs/DoubleEndedQueue.sol";
A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of
the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and
FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes clear
, given that
the existing queue contents are left in storage.
The struct is called Bytes32Deque
. Other types can be cast to and from bytes32
. This data structure can only be
used in storage, and not in memory.
DoubleEndedQueue.Bytes32Deque queue;
Available since v4.6.
pushBack(struct DoubleEndedQueue.Bytes32Deque deque, bytes32 value)
internal
Inserts an item at the end of the queue.
popBack(struct DoubleEndedQueue.Bytes32Deque deque) → bytes32 value
internal
Removes the item at the end of the queue and returns it.
Reverts with Empty
if the queue is empty.
pushFront(struct DoubleEndedQueue.Bytes32Deque deque, bytes32 value)
internal
Inserts an item at the beginning of the queue.
popFront(struct DoubleEndedQueue.Bytes32Deque deque) → bytes32 value
internal
Removes the item at the beginning of the queue and returns it.
Reverts with Empty
if the queue is empty.
front(struct DoubleEndedQueue.Bytes32Deque deque) → bytes32 value
internal
Returns the item at the beginning of the queue.
Reverts with Empty
if the queue is empty.
back(struct DoubleEndedQueue.Bytes32Deque deque) → bytes32 value
internal
Returns the item at the end of the queue.
Reverts with Empty
if the queue is empty.
at(struct DoubleEndedQueue.Bytes32Deque deque, uint256 index) → bytes32 value
internal
Return the item at a position in the queue given by index
, with the first item at 0 and last item at
length(deque) - 1
.
Reverts with OutOfBounds
if the index is out of bounds.
clear(struct DoubleEndedQueue.Bytes32Deque deque)
internal
Resets the queue back to being empty.
The current items are left behind in storage. This does not affect the functioning of the queue, but misses out on potential gas refunds. |
Checkpoints
import "@openzeppelin/contracts/utils/Checkpoints.sol";
This library defines the History
struct, for checkpointing values as they change at different points in
time, and later looking up past values by block number. See Votes
as an example.
To create a history of checkpoints define a variable type Checkpoints.History
in your contract, and store a new
checkpoint for the current transaction block using the push
function.
Available since v4.5.
latest(struct Checkpoints.History self) → uint256
internal
Returns the value in the latest checkpoint, or zero if there are no checkpoints.
getAtBlock(struct Checkpoints.History self, uint256 blockNumber) → uint256
internal
Returns the value at a given block number. If a checkpoint is not available at that block, the closest one before it is returned, or zero otherwise.
push(struct Checkpoints.History self, uint256 value) → uint256, uint256
internal
Pushes a value onto a History so that it is stored as the checkpoint for the current block.
Returns previous value and new value.
push(struct Checkpoints.History self, function (uint256,uint256) view returns (uint256) op, uint256 delta) → uint256, uint256
internal
Pushes a value onto a History, by updating the latest value using binary operation op
. The new value will
be set to op(latest, delta)
.
Returns previous value and new value.
Libraries
Create2
import "@openzeppelin/contracts/utils/Create2.sol";
Helper to make usage of the CREATE2
EVM opcode easier and safer.
CREATE2
can be used to compute in advance the address where a smart
contract will be deployed, which allows for interesting new mechanisms known
as 'counterfactual interactions'.
See the EIP for more information.
deploy(uint256 amount, bytes32 salt, bytes bytecode) → address
internal
Deploys a contract using CREATE2
. The address where the contract
will be deployed can be known in advance via computeAddress
.
The bytecode for a contract can be obtained from Solidity with
type(contractName).creationCode
.
Requirements:
-
bytecode
must not be empty. -
salt
must have not been used forbytecode
already. -
the factory must have a balance of at least
amount
. -
if
amount
is non-zero,bytecode
must have apayable
constructor.
computeAddress(bytes32 salt, bytes32 bytecodeHash) → address
internal
Returns the address where a contract will be stored if deployed via deploy
. Any change in the
bytecodeHash
or salt
will result in a new destination address.
computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) → address
internal
Returns the address where a contract will be stored if deployed via deploy
from a contract located at
deployer
. If deployer
is this contract’s address, returns the same value as computeAddress
.
Address
import "@openzeppelin/contracts/utils/Address.sol";
Collection of functions related to the address type
isContract(address account) → bool
internal
Returns true if account
is a contract.
It is unsafe to assume that an address for which this function returns false is an externally-owned account (EOA) and not a contract. Among others,
|
You shouldn’t rely on Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract constructor. |
sendValue(address payable recipient, uint256 amount)
internal
Replacement for Solidity’s transfer
: sends amount
wei to
recipient
, forwarding all available gas and reverting on errors.
EIP1884 increases the gas cost
of certain opcodes, possibly making contracts go over the 2300 gas limit
imposed by transfer
, making them unable to receive funds via
transfer
. sendValue
removes this limitation.
because control is transferred to recipient , care must be
taken to not create reentrancy vulnerabilities. Consider using
ReentrancyGuard or the
checks-effects-interactions pattern.
|
functionCall(address target, bytes data) → bytes
internal
Performs a Solidity function call using a low level call
. A
plain call
is an unsafe replacement for a function call: use this
function instead.
If target
reverts with a revert reason, it is bubbled up by this
function (like regular Solidity function calls).
Returns the raw returned data. To convert to the expected return value,
use abi.decode
.
Requirements:
-
target
must be a contract. -
calling
target
withdata
must not revert.
Available since v3.1.
functionCall(address target, bytes data, string errorMessage) → bytes
internal
Same as functionCall
, but with
errorMessage
as a fallback revert reason when target
reverts.
Available since v3.1.
functionCallWithValue(address target, bytes data, uint256 value) → bytes
internal
Same as functionCall
,
but also transferring value
wei to target
.
Requirements:
-
the calling contract must have an ETH balance of at least
value
. -
the called Solidity function must be
payable
.
Available since v3.1.
functionCallWithValue(address target, bytes data, uint256 value, string errorMessage) → bytes
internal
Same as functionCallWithValue
, but
with errorMessage
as a fallback revert reason when target
reverts.
Available since v3.1.
functionStaticCall(address target, bytes data) → bytes
internal
Same as functionCall
,
but performing a static call.
Available since v3.3.
functionStaticCall(address target, bytes data, string errorMessage) → bytes
internal
Same as functionCall
,
but performing a static call.
Available since v3.3.
functionDelegateCall(address target, bytes data) → bytes
internal
Same as functionCall
,
but performing a delegate call.
Available since v3.4.
functionDelegateCall(address target, bytes data, string errorMessage) → bytes
internal
Same as functionCall
,
but performing a delegate call.
Available since v3.4.
Arrays
import "@openzeppelin/contracts/utils/Arrays.sol";
Collection of functions related to array types.
findUpperBound(uint256[] array, uint256 element) → uint256
internal
Searches a sorted array
and returns the first index that contains
a value greater or equal to element
. If no such index exists (i.e. all
values in the array are strictly less than element
), the array length is
returned. Time complexity O(log n).
array
is expected to be sorted in ascending order, and to contain no
repeated elements.
Base64
import "@openzeppelin/contracts/utils/Base64.sol";
Provides a set of functions to operate with Base64 strings.
Available since v4.5.
Counters
import "@openzeppelin/contracts/utils/Counters.sol";
Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number of elements in a mapping, issuing ERC721 ids, or counting request ids.
Include with using Counters for Counters.Counter;
Strings
import "@openzeppelin/contracts/utils/Strings.sol";
String operations.
toString(uint256 value) → string
internal
Converts a uint256
to its ASCII string
decimal representation.
StorageSlot
import "@openzeppelin/contracts/utils/StorageSlot.sol";
Library for reading and writing primitive types to specific storage slots.
Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. This library helps with reading and writing to such slots without the need for inline assembly.
The functions in this library return Slot structs that contain a value
member that can be used to read or write.
Example usage to set ERC1967 implementation slot:
contract ERC1967 {
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
}
Available since v4.1 for address
, bool
, bytes32
, and uint256
.
getAddressSlot(bytes32 slot) → struct StorageSlot.AddressSlot r
internal
Returns an AddressSlot
with member value
located at slot
.
getBooleanSlot(bytes32 slot) → struct StorageSlot.BooleanSlot r
internal
Returns an BooleanSlot
with member value
located at slot
.