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.
-
Math
,SignedMath
: Implementation of various arithmetic functions. -
SafeCast
: Checked downcasting functions to avoid silent truncation. -
ECDSA
,MessageHashUtils
: Libraries for interacting with ECDSA signatures. -
SignatureChecker
: A library helper to support regular ECDSA from EOAs as well as ERC-1271 signatures for smart contracts. -
MerkleProof
: Functions for verifying Merkle Tree proofs. -
EIP712
: Contract with functions to allow processing signed typed structure data according to EIP-712. -
ReentrancyGuard
: A modifier that can prevent reentrancy during certain functions. -
Pausable
: A common emergency response mechanism that can pause functionality while a remediation is pending. -
Nonces
: Utility for tracking and verifying address nonces that only increment. -
{ERC165, ERC165Checker}: Utilities for inspecting interfaces supported by contracts.
-
BitMaps
: A simple library to manage boolean value mapped to a numerical index in an efficient way. -
EnumerableMap
: A type like Solidity’smapping
, 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. -
DoubleEndedQueue
: An implementation of a double ended queue whose values can be removed added or remove from both sides. Useful for FIFO and LIFO structures. -
Checkpoints
: A data structure to store values mapped to an strictly increasing key. Can be used for storing and accessing values over time. -
Create2
: Wrapper around theCREATE2
EVM opcode for safe use without having to deal with low-level assembly. -
Address
: Collection of functions for overloading Solidity’saddress
type. -
Base64
: On-chain base64 and base64URL encoding according to RFC-4648. -
Strings
: Common operations for strings formatting. -
ShortString
: Library to encode (and decode) short strings into (or from) a single bytes32 slot for optimizing costs. Short strings are limited to 31 characters. -
StorageSlot
: Methods for accessing specific storage slots formatted as common primitive types. -
Multicall
: Abstract contract with an utility to allow batching together multiple calls in a single transaction. Useful for allowing EOAs to perform multiple operations at once. -
Context
: An utility for abstracting the sender and calldata in the current execution context.
Because Solidity does not support generic types, |
Math
Math
import "@openzeppelin/contracts/utils/math/Math.sol";
Standard math utilities missing in the Solidity language.
tryAdd(uint256 a, uint256 b) → bool, uint256
internal
Returns the addition of two unsigned integers, with an overflow flag.
trySub(uint256 a, uint256 b) → bool, uint256
internal
Returns the subtraction of two unsigned integers, with an overflow flag.
tryMul(uint256 a, uint256 b) → bool, uint256
internal
Returns the multiplication of two unsigned integers, with an overflow flag.
tryDiv(uint256 a, uint256 b) → bool, uint256
internal
Returns the division of two unsigned integers, with a division by zero flag.
tryMod(uint256 a, uint256 b) → bool, uint256
internal
Returns the remainder of dividing two unsigned integers, with a division by zero flag.
average(uint256 a, uint256 b) → uint256
internal
Returns the average of two numbers. The result is rounded towards zero.
ceilDiv(uint256 a, uint256 b) → uint256
internal
Returns the ceiling of the division of two numbers.
This differs from standard division with /
in that it rounds towards infinity instead
of rounding towards zero.
mulDiv(uint256 x, uint256 y, uint256 denominator) → uint256 result
internal
Original credit to Remco Bloemen under MIT license (https://xn—2-umb.com/21/muldiv) with further edits by Uniswap Labs also under MIT license.
sqrt(uint256 a) → uint256
internal
Returns the square root of a number. If the number is not a perfect square, the value is rounded towards zero.
Inspired by Henry S. Warren, Jr.'s "Hacker’s Delight" (Chapter 11).
log2(uint256 value) → uint256
internal
Return the log in base 2 of a positive value rounded towards zero. Returns 0 if given 0.
log2(uint256 value, enum Math.Rounding rounding) → uint256
internal
Return the log in base 2, following the selected rounding direction, of a positive value. Returns 0 if given 0.
log10(uint256 value) → uint256
internal
Return the log in base 10 of a positive value rounded towards zero. Returns 0 if given 0.
log10(uint256 value, enum Math.Rounding rounding) → uint256
internal
Return the log in base 10, following the selected rounding direction, of a positive value. Returns 0 if given 0.
log256(uint256 value) → uint256
internal
Return the log in base 256 of a positive value rounded towards zero. Returns 0 if given 0.
Adding one to the result gives the number of pairs of hex symbols needed to represent value
as a hex string.
log256(uint256 value, enum Math.Rounding rounding) → uint256
internal
Return the log in base 256, following the selected rounding direction, of a positive value. Returns 0 if given 0.
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.
toUint248(uint256 value) → uint248
internal
Returns the downcasted uint248 from uint256, reverting on overflow (when the input is greater than largest uint248).
Counterpart to Solidity’s uint248
operator.
Requirements:
-
input must fit into 248 bits
toUint240(uint256 value) → uint240
internal
Returns the downcasted uint240 from uint256, reverting on overflow (when the input is greater than largest uint240).
Counterpart to Solidity’s uint240
operator.
Requirements:
-
input must fit into 240 bits
toUint232(uint256 value) → uint232
internal
Returns the downcasted uint232 from uint256, reverting on overflow (when the input is greater than largest uint232).
Counterpart to Solidity’s uint232
operator.
Requirements:
-
input must fit into 232 bits
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
toUint216(uint256 value) → uint216
internal
Returns the downcasted uint216 from uint256, reverting on overflow (when the input is greater than largest uint216).
Counterpart to Solidity’s uint216
operator.
Requirements:
-
input must fit into 216 bits
toUint208(uint256 value) → uint208
internal
Returns the downcasted uint208 from uint256, reverting on overflow (when the input is greater than largest uint208).
Counterpart to Solidity’s uint208
operator.
Requirements:
-
input must fit into 208 bits
toUint200(uint256 value) → uint200
internal
Returns the downcasted uint200 from uint256, reverting on overflow (when the input is greater than largest uint200).
Counterpart to Solidity’s uint200
operator.
Requirements:
-
input must fit into 200 bits
toUint192(uint256 value) → uint192
internal
Returns the downcasted uint192 from uint256, reverting on overflow (when the input is greater than largest uint192).
Counterpart to Solidity’s uint192
operator.
Requirements:
-
input must fit into 192 bits
toUint184(uint256 value) → uint184
internal
Returns the downcasted uint184 from uint256, reverting on overflow (when the input is greater than largest uint184).
Counterpart to Solidity’s uint184
operator.
Requirements:
-
input must fit into 184 bits
toUint176(uint256 value) → uint176
internal
Returns the downcasted uint176 from uint256, reverting on overflow (when the input is greater than largest uint176).
Counterpart to Solidity’s uint176
operator.
Requirements:
-
input must fit into 176 bits
toUint168(uint256 value) → uint168
internal
Returns the downcasted uint168 from uint256, reverting on overflow (when the input is greater than largest uint168).
Counterpart to Solidity’s uint168
operator.
Requirements:
-
input must fit into 168 bits
toUint160(uint256 value) → uint160
internal
Returns the downcasted uint160 from uint256, reverting on overflow (when the input is greater than largest uint160).
Counterpart to Solidity’s uint160
operator.
Requirements:
-
input must fit into 160 bits
toUint152(uint256 value) → uint152
internal
Returns the downcasted uint152 from uint256, reverting on overflow (when the input is greater than largest uint152).
Counterpart to Solidity’s uint152
operator.
Requirements:
-
input must fit into 152 bits
toUint144(uint256 value) → uint144
internal
Returns the downcasted uint144 from uint256, reverting on overflow (when the input is greater than largest uint144).
Counterpart to Solidity’s uint144
operator.
Requirements:
-
input must fit into 144 bits
toUint136(uint256 value) → uint136
internal
Returns the downcasted uint136 from uint256, reverting on overflow (when the input is greater than largest uint136).
Counterpart to Solidity’s uint136
operator.
Requirements:
-
input must fit into 136 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
toUint120(uint256 value) → uint120
internal
Returns the downcasted uint120 from uint256, reverting on overflow (when the input is greater than largest uint120).
Counterpart to Solidity’s uint120
operator.
Requirements:
-
input must fit into 120 bits
toUint112(uint256 value) → uint112
internal
Returns the downcasted uint112 from uint256, reverting on overflow (when the input is greater than largest uint112).
Counterpart to Solidity’s uint112
operator.
Requirements:
-
input must fit into 112 bits
toUint104(uint256 value) → uint104
internal
Returns the downcasted uint104 from uint256, reverting on overflow (when the input is greater than largest uint104).
Counterpart to Solidity’s uint104
operator.
Requirements:
-
input must fit into 104 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
toUint88(uint256 value) → uint88
internal
Returns the downcasted uint88 from uint256, reverting on overflow (when the input is greater than largest uint88).
Counterpart to Solidity’s uint88
operator.
Requirements:
-
input must fit into 88 bits
toUint80(uint256 value) → uint80
internal
Returns the downcasted uint80 from uint256, reverting on overflow (when the input is greater than largest uint80).
Counterpart to Solidity’s uint80
operator.
Requirements:
-
input must fit into 80 bits
toUint72(uint256 value) → uint72
internal
Returns the downcasted uint72 from uint256, reverting on overflow (when the input is greater than largest uint72).
Counterpart to Solidity’s uint72
operator.
Requirements:
-
input must fit into 72 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
toUint56(uint256 value) → uint56
internal
Returns the downcasted uint56 from uint256, reverting on overflow (when the input is greater than largest uint56).
Counterpart to Solidity’s uint56
operator.
Requirements:
-
input must fit into 56 bits
toUint48(uint256 value) → uint48
internal
Returns the downcasted uint48 from uint256, reverting on overflow (when the input is greater than largest uint48).
Counterpart to Solidity’s uint48
operator.
Requirements:
-
input must fit into 48 bits
toUint40(uint256 value) → uint40
internal
Returns the downcasted uint40 from uint256, reverting on overflow (when the input is greater than largest uint40).
Counterpart to Solidity’s uint40
operator.
Requirements:
-
input must fit into 40 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
toUint24(uint256 value) → uint24
internal
Returns the downcasted uint24 from uint256, reverting on overflow (when the input is greater than largest uint24).
Counterpart to Solidity’s uint24
operator.
Requirements:
-
input must fit into 24 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.
toInt248(int256 value) → int248 downcasted
internal
Returns the downcasted int248 from int256, reverting on overflow (when the input is less than smallest int248 or greater than largest int248).
Counterpart to Solidity’s int248
operator.
Requirements:
-
input must fit into 248 bits
toInt240(int256 value) → int240 downcasted
internal
Returns the downcasted int240 from int256, reverting on overflow (when the input is less than smallest int240 or greater than largest int240).
Counterpart to Solidity’s int240
operator.
Requirements:
-
input must fit into 240 bits
toInt232(int256 value) → int232 downcasted
internal
Returns the downcasted int232 from int256, reverting on overflow (when the input is less than smallest int232 or greater than largest int232).
Counterpart to Solidity’s int232
operator.
Requirements:
-
input must fit into 232 bits
toInt224(int256 value) → int224 downcasted
internal
Returns the downcasted int224 from int256, reverting on overflow (when the input is less than smallest int224 or greater than largest int224).
Counterpart to Solidity’s int224
operator.
Requirements:
-
input must fit into 224 bits
toInt216(int256 value) → int216 downcasted
internal
Returns the downcasted int216 from int256, reverting on overflow (when the input is less than smallest int216 or greater than largest int216).
Counterpart to Solidity’s int216
operator.
Requirements:
-
input must fit into 216 bits
toInt208(int256 value) → int208 downcasted
internal
Returns the downcasted int208 from int256, reverting on overflow (when the input is less than smallest int208 or greater than largest int208).
Counterpart to Solidity’s int208
operator.
Requirements:
-
input must fit into 208 bits
toInt200(int256 value) → int200 downcasted
internal
Returns the downcasted int200 from int256, reverting on overflow (when the input is less than smallest int200 or greater than largest int200).
Counterpart to Solidity’s int200
operator.
Requirements:
-
input must fit into 200 bits
toInt192(int256 value) → int192 downcasted
internal
Returns the downcasted int192 from int256, reverting on overflow (when the input is less than smallest int192 or greater than largest int192).
Counterpart to Solidity’s int192
operator.
Requirements:
-
input must fit into 192 bits
toInt184(int256 value) → int184 downcasted
internal
Returns the downcasted int184 from int256, reverting on overflow (when the input is less than smallest int184 or greater than largest int184).
Counterpart to Solidity’s int184
operator.
Requirements:
-
input must fit into 184 bits
toInt176(int256 value) → int176 downcasted
internal
Returns the downcasted int176 from int256, reverting on overflow (when the input is less than smallest int176 or greater than largest int176).
Counterpart to Solidity’s int176
operator.
Requirements:
-
input must fit into 176 bits
toInt168(int256 value) → int168 downcasted
internal
Returns the downcasted int168 from int256, reverting on overflow (when the input is less than smallest int168 or greater than largest int168).
Counterpart to Solidity’s int168
operator.
Requirements:
-
input must fit into 168 bits
toInt160(int256 value) → int160 downcasted
internal
Returns the downcasted int160 from int256, reverting on overflow (when the input is less than smallest int160 or greater than largest int160).
Counterpart to Solidity’s int160
operator.
Requirements:
-
input must fit into 160 bits
toInt152(int256 value) → int152 downcasted
internal
Returns the downcasted int152 from int256, reverting on overflow (when the input is less than smallest int152 or greater than largest int152).
Counterpart to Solidity’s int152
operator.
Requirements:
-
input must fit into 152 bits
toInt144(int256 value) → int144 downcasted
internal
Returns the downcasted int144 from int256, reverting on overflow (when the input is less than smallest int144 or greater than largest int144).
Counterpart to Solidity’s int144
operator.
Requirements:
-
input must fit into 144 bits
toInt136(int256 value) → int136 downcasted
internal
Returns the downcasted int136 from int256, reverting on overflow (when the input is less than smallest int136 or greater than largest int136).
Counterpart to Solidity’s int136
operator.
Requirements:
-
input must fit into 136 bits
toInt128(int256 value) → int128 downcasted
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
toInt120(int256 value) → int120 downcasted
internal
Returns the downcasted int120 from int256, reverting on overflow (when the input is less than smallest int120 or greater than largest int120).
Counterpart to Solidity’s int120
operator.
Requirements:
-
input must fit into 120 bits
toInt112(int256 value) → int112 downcasted
internal
Returns the downcasted int112 from int256, reverting on overflow (when the input is less than smallest int112 or greater than largest int112).
Counterpart to Solidity’s int112
operator.
Requirements:
-
input must fit into 112 bits
toInt104(int256 value) → int104 downcasted
internal
Returns the downcasted int104 from int256, reverting on overflow (when the input is less than smallest int104 or greater than largest int104).
Counterpart to Solidity’s int104
operator.
Requirements:
-
input must fit into 104 bits
toInt96(int256 value) → int96 downcasted
internal
Returns the downcasted int96 from int256, reverting on overflow (when the input is less than smallest int96 or greater than largest int96).
Counterpart to Solidity’s int96
operator.
Requirements:
-
input must fit into 96 bits
toInt88(int256 value) → int88 downcasted
internal
Returns the downcasted int88 from int256, reverting on overflow (when the input is less than smallest int88 or greater than largest int88).
Counterpart to Solidity’s int88
operator.
Requirements:
-
input must fit into 88 bits
toInt80(int256 value) → int80 downcasted
internal
Returns the downcasted int80 from int256, reverting on overflow (when the input is less than smallest int80 or greater than largest int80).
Counterpart to Solidity’s int80
operator.
Requirements:
-
input must fit into 80 bits
toInt72(int256 value) → int72 downcasted
internal
Returns the downcasted int72 from int256, reverting on overflow (when the input is less than smallest int72 or greater than largest int72).
Counterpart to Solidity’s int72
operator.
Requirements:
-
input must fit into 72 bits
toInt64(int256 value) → int64 downcasted
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
toInt56(int256 value) → int56 downcasted
internal
Returns the downcasted int56 from int256, reverting on overflow (when the input is less than smallest int56 or greater than largest int56).
Counterpart to Solidity’s int56
operator.
Requirements:
-
input must fit into 56 bits
toInt48(int256 value) → int48 downcasted
internal
Returns the downcasted int48 from int256, reverting on overflow (when the input is less than smallest int48 or greater than largest int48).
Counterpart to Solidity’s int48
operator.
Requirements:
-
input must fit into 48 bits
toInt40(int256 value) → int40 downcasted
internal
Returns the downcasted int40 from int256, reverting on overflow (when the input is less than smallest int40 or greater than largest int40).
Counterpart to Solidity’s int40
operator.
Requirements:
-
input must fit into 40 bits
toInt32(int256 value) → int32 downcasted
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
toInt24(int256 value) → int24 downcasted
internal
Returns the downcasted int24 from int256, reverting on overflow (when the input is less than smallest int24 or greater than largest int24).
Counterpart to Solidity’s int24
operator.
Requirements:
-
input must fit into 24 bits
toInt16(int256 value) → int16 downcasted
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
toInt8(int256 value) → int8 downcasted
internal
Returns the downcasted int8 from int256, reverting on overflow (when the input is less than smallest int8 or greater than largest int8).
Counterpart to Solidity’s int8
operator.
Requirements:
-
input must fit into 8 bits
toInt256(uint256 value) → int256
internal
Converts an unsigned uint256 into a signed int256.
Requirements:
-
input must be less than or equal to maxInt256.
SafeCastOverflowedUintDowncast(uint8 bits, uint256 value)
error
Value doesn’t fit in an uint of bits
size.
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, bytes32
internal
Returns the address that signed a hashed message (hash
) with signature
or an error. This will not
return address(0) without also returning an error description. Errors are documented using an enum (error type)
and a bytes32 providing additional information about the error.
If no error is returned, then the address can be used for verification purposes.
The ecrecover
EVM precompile 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 MessageHashUtils.toEthSignedMessageHash on it.
|
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 precompile 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 MessageHashUtils.toEthSignedMessageHash on it.
|
tryRecover(bytes32 hash, bytes32 r, bytes32 vs) → address, enum ECDSA.RecoverError, bytes32
internal
Overload of ECDSA.tryRecover
that receives the r
and vs
short-signature fields separately.
recover(bytes32 hash, bytes32 r, bytes32 vs) → address
internal
Overload of ECDSA.recover
that receives the r and `vs
short-signature fields separately.
tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) → address, enum ECDSA.RecoverError, bytes32
internal
Overload of ECDSA.tryRecover
that receives the v
,
r
and s
signature fields separately.
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.
MessageHashUtils
import "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
Signature message hash utilities for producing digests to be consumed by ECDSA
recovery or signing.
The library provides methods for generating a hash of a message that conforms to the EIP 191 and EIP 712 specifications.
toEthSignedMessageHash(bytes32 messageHash) → bytes32 digest
internal
Returns the keccak256 digest of an EIP-191 signed data with version
0x45
(personal_sign
messages).
The digest is calculated by prefixing a bytes32 messageHash
with
"\x19Ethereum Signed Message:\n32"
and hashing the result. It corresponds with the
hash signed when using the eth_sign
JSON-RPC method.
The messageHash parameter is intended to be the result of hashing a raw message with
keccak256, although any bytes32 value can be safely used because the final digest will
be re-hashed.
|
See ECDSA.recover
.
toEthSignedMessageHash(bytes message) → bytes32
internal
Returns the keccak256 digest of an EIP-191 signed data with version
0x45
(personal_sign
messages).
The digest is calculated by prefixing an arbitrary message
with
"\x19Ethereum Signed Message:\n" + len(message)
and hashing the result. It corresponds with the
hash signed when using the eth_sign
JSON-RPC method.
See ECDSA.recover
.
toDataWithIntendedValidatorHash(address validator, bytes data) → bytes32
internal
Returns the keccak256 digest of an EIP-191 signed data with version
0x00
(data with intended validator).
The digest is calculated by prefixing an arbitrary data
with "\x19\x00"
and the intended
validator
address. Then hashing the result.
See ECDSA.recover
.
toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) → bytes32 digest
internal
Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version 0x01
).
The digest is calculated from a domainSeparator
and a structHash
, by prefixing them with
\x19\x01
and hashing the result. It corresponds to the hash signed by the
eth_signTypedData
JSON-RPC method as part of EIP-712.
See ECDSA.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 Safe Wallet (previously Gnosis Safe).
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). |
isValidERC1271SignatureNow(address signer, bytes32 hash, bytes signature) → bool
internal
Checks if a signature is valid for a given signer and data hash. The signature is validated against the signer smart contract using ERC1271.
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 Tree proofs.
The tree and the proofs can be generated using our JavaScript library. You will find a quickstart guide in the readme.
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. OpenZeppelin’s JavaScript library generates Merkle trees that are safe against this attack out of the box. |
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.
verifyCalldata(bytes32[] proof, bytes32 root, bytes32 leaf) → bool
internal
Calldata version of verify
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.
processProofCalldata(bytes32[] proof, bytes32 leaf) → bytes32
internal
Calldata version of processProof
multiProofVerify(bytes32[] proof, bool[] proofFlags, bytes32 root, bytes32[] leaves) → bool
internal
Returns true if the leaves
can be simultaneously proven to be a part of a Merkle tree defined by
root
, according to proof
and proofFlags
as described in processMultiProof
.
Not all Merkle trees admit multiproofs. See processMultiProof for details.
|
multiProofVerifyCalldata(bytes32[] proof, bool[] proofFlags, bytes32 root, bytes32[] leaves) → bool
internal
Calldata version of multiProofVerify
Not all Merkle trees admit multiproofs. See processMultiProof for details.
|
processMultiProof(bytes32[] proof, bool[] proofFlags, bytes32[] leaves) → bytes32 merkleRoot
internal
Returns the root of a tree reconstructed from leaves
and sibling nodes in proof
. The reconstruction
proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
leaf/inner node or a proof sibling node, depending on whether each proofFlags
item is true or false
respectively.
Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). |
processMultiProofCalldata(bytes32[] proof, bool[] proofFlags, bytes32[] leaves) → bytes32 merkleRoot
internal
Calldata version of processMultiProof
.
Not all Merkle trees admit multiproofs. See processMultiProof for details.
|
EIP712
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
EIP 712 is a standard for hashing and signing of typed structured data.
The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
encoding is very generic and therefore its 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 order to
produce the hash of their typed data 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.
|
In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
separator of the implementation contract. This will cause the _domainSeparatorV4 function to always rebuild the
separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
|
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);
eip712Domain() → bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions
public
See {IERC-5267}.
Security
ReentrancyGuard
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
Contract module that helps prevent reentrant calls to a function.
Inheriting from ReentrancyGuard
will make the nonReentrant
modifier
available, which can be applied to functions to make sure there are no nested
(reentrant) calls to them.
Note that because there is a single nonReentrant
guard, functions marked as
nonReentrant
may not call one another. This can be worked around by making
those functions private
, and then adding external
nonReentrant
entry
points to them.
If you would like to learn more about reentrancy and alternative ways to protect against it, check out our blog post Reentrancy After Istanbul. |
nonReentrant()
modifier
Prevents a contract from calling itself, directly or indirectly.
Calling a nonReentrant
function from another nonReentrant
function is not supported. It is possible to prevent this from happening
by making the nonReentrant
function external, and making it call a
private
function that does the actual work.
Pausable
import "@openzeppelin/contracts/utils/Pausable.sol";
Contract module which allows children to implement an emergency stop mechanism that can be triggered by an authorized account.
This module is used through inheritance. It will make available the
modifiers whenNotPaused
and whenPaused
, which can be applied to
the functions of your contract. Note that they will not be pausable by
simply including this module, only once the modifiers are put in place.
whenNotPaused()
modifier
Modifier to make a function callable only when the contract is not paused.
Requirements:
-
The contract must not be paused.
Nonces
import "@openzeppelin/contracts/utils/Nonces.sol";
Provides tracking nonces for addresses. Nonces will only increment.
_useNonce(address owner) → uint256
internal
Consumes a nonce.
Returns the current value and increments nonce.
_useCheckedNonce(address owner, uint256 nonce)
internal
Same as _useNonce
but checking that nonce
is the next valid for owner
.
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.
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);
}
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.
supportsAllInterfaces(address account, bytes4[] interfaceIds) → bool
internal
Returns true if account
supports all the interfaces defined in
interfaceIds
. Support for IERC165
itself is queried automatically.
Batch-querying can lead to gas savings by skipping repeated checks for
IERC165
support.
supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) → bool
internal
Assumes that account contains a contract that supports ERC165, otherwise
the behavior of this method is undefined. This precondition can be checked
with supportsERC165
.
Some precompiled contracts will falsely indicate support for a given interface, so caution should be exercised when using this function.
Interface identification is specified in ERC-165.
Data Structures
BitMaps
import "@openzeppelin/contracts/utils/structs/BitMaps.sol";
Library for managing uint256 to bool mapping in a compact and efficient way, provided the keys are sequential. Largely inspired by Uniswap’s merkle-distributor.
BitMaps pack 256 booleans across each bit of a single 256-bit slot of uint256
type.
Hence booleans corresponding to 256 sequential indices would only consume a single slot,
unlike the regular bool
which would consume an entire slot for a single value.
This results in gas savings in two ways:
-
Setting a zero value to non-zero only once every 256 times
-
Accessing the same warm slot for every 256 sequential indices
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
(Bytes32ToBytes32Map
) since v4.6.0 -
uint256 → uint256
(UintToUintMap
) since v4.7.0 -
bytes32 → uint256
(Bytes32ToUintMap
) since v4.7.0
Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable. See ethereum/solidity#11843 for more info. In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an array of EnumerableMap. |
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.
keys(struct EnumerableMap.Bytes32ToBytes32Map map) → bytes32[]
internal
Return the an array containing all the keys
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 map grows to a point where copying to memory consumes too much gas to fit in a block. |
set(struct EnumerableMap.UintToUintMap map, uint256 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.UintToUintMap map, uint256 key) → bool
internal
Removes a value from a map. O(1).
Returns true if the key was removed from the map, that is if it was present.
contains(struct EnumerableMap.UintToUintMap map, uint256 key) → bool
internal
Returns true if the key is in the map. O(1).
length(struct EnumerableMap.UintToUintMap map) → uint256
internal
Returns the number of elements in the map. O(1).
at(struct EnumerableMap.UintToUintMap map, uint256 index) → uint256, uint256
internal
Returns the element stored at position index
in the map. 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.UintToUintMap map, uint256 key) → bool, uint256
internal
Tries to returns the value associated with key
. O(1).
Does not revert if key
is not in the map.
get(struct EnumerableMap.UintToUintMap map, uint256 key) → uint256
internal
Returns the value associated with key
. O(1).
Requirements:
-
key
must be in the map.
keys(struct EnumerableMap.UintToUintMap map) → uint256[]
internal
Return the an array containing all the keys
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 map grows to a point where copying to memory consumes too much gas to fit in a block. |
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 map. 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 map. 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.
get(struct EnumerableMap.UintToAddressMap map, uint256 key) → address
internal
Returns the value associated with key
. O(1).
Requirements:
-
key
must be in the map.
keys(struct EnumerableMap.UintToAddressMap map) → uint256[]
internal
Return the an array containing all the keys
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 map grows to a point where copying to memory consumes too much gas to fit in a block. |
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 map. 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 map. 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.
get(struct EnumerableMap.AddressToUintMap map, address key) → uint256
internal
Returns the value associated with key
. O(1).
Requirements:
-
key
must be in the map.
keys(struct EnumerableMap.AddressToUintMap map) → address[]
internal
Return the an array containing all the keys
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 map grows to a point where copying to memory consumes too much gas to fit in a block. |
set(struct EnumerableMap.Bytes32ToUintMap map, bytes32 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.Bytes32ToUintMap map, bytes32 key) → bool
internal
Removes a value from a map. O(1).
Returns true if the key was removed from the map, that is if it was present.
contains(struct EnumerableMap.Bytes32ToUintMap map, bytes32 key) → bool
internal
Returns true if the key is in the map. O(1).
length(struct EnumerableMap.Bytes32ToUintMap map) → uint256
internal
Returns the number of elements in the map. O(1).
at(struct EnumerableMap.Bytes32ToUintMap map, uint256 index) → bytes32, uint256
internal
Returns the element stored at position index
in the map. 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.Bytes32ToUintMap map, bytes32 key) → bool, uint256
internal
Tries to returns the value associated with key
. O(1).
Does not revert if key
is not in the map.
get(struct EnumerableMap.Bytes32ToUintMap map, bytes32 key) → uint256
internal
Returns the value associated with key
. O(1).
Requirements:
-
key
must be in the map.
keys(struct EnumerableMap.Bytes32ToUintMap map) → bytes32[]
internal
Return the an array containing all the keys
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 map grows to a point where copying to memory consumes too much gas to fit in a block. |
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.
Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable. See ethereum/solidity#11843 for more info. In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet. |
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 in 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;
pushBack(struct DoubleEndedQueue.Bytes32Deque deque, bytes32 value)
internal
Inserts an item at the end of the queue.
Reverts with QueueFull
if the queue is full.
popBack(struct DoubleEndedQueue.Bytes32Deque deque) → bytes32 value
internal
Removes the item at the end of the queue and returns it.
Reverts with QueueEmpty
if the queue is empty.
pushFront(struct DoubleEndedQueue.Bytes32Deque deque, bytes32 value)
internal
Inserts an item at the beginning of the queue.
Reverts with QueueFull
if the queue is full.
popFront(struct DoubleEndedQueue.Bytes32Deque deque) → bytes32 value
internal
Removes the item at the beginning of the queue and returns it.
Reverts with QueueEmpty
if the queue is empty.
front(struct DoubleEndedQueue.Bytes32Deque deque) → bytes32 value
internal
Returns the item at the beginning of the queue.
Reverts with QueueEmpty
if the queue is empty.
back(struct DoubleEndedQueue.Bytes32Deque deque) → bytes32 value
internal
Returns the item at the end of the queue.
Reverts with QueueEmpty
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 QueueOutOfBounds
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. |
length(struct DoubleEndedQueue.Bytes32Deque deque) → uint256
internal
Returns the number of items in the queue.
empty(struct DoubleEndedQueue.Bytes32Deque deque) → bool
internal
Returns true if the queue is empty.
QueueEmpty()
error
An operation (e.g. front
) couldn’t be completed due to the queue being empty.
QueueOutOfBounds()
error
An operation (e.g. at
) couldn’t be completed due to an index being out of bounds.
Checkpoints
import "@openzeppelin/contracts/utils/structs/Checkpoints.sol";
This library defines the Trace*
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.Trace*
in your contract, and store a new
checkpoint for the current transaction block using the push
function.
push(struct Checkpoints.Trace224 self, uint32 key, uint224 value) → uint224, uint224
internal
Pushes a (key
, value
) pair into a Trace224 so that it is stored as the checkpoint.
Returns previous value and new value.
Never accept key as a user input, since an arbitrary type(uint32).max key set will disable the
library.
|
lowerLookup(struct Checkpoints.Trace224 self, uint32 key) → uint224
internal
Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if there is none.
upperLookup(struct Checkpoints.Trace224 self, uint32 key) → uint224
internal
Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none.
upperLookupRecent(struct Checkpoints.Trace224 self, uint32 key) → uint224
internal
Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none.
This is a variant of upperLookup that is optimised to find "recent" checkpoint (checkpoints with high
keys).
|
latest(struct Checkpoints.Trace224 self) → uint224
internal
Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
latestCheckpoint(struct Checkpoints.Trace224 self) → bool exists, uint32 _key, uint224 _value
internal
Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value in the most recent checkpoint.
at(struct Checkpoints.Trace224 self, uint32 pos) → struct Checkpoints.Checkpoint224
internal
Returns checkpoint at given position.
push(struct Checkpoints.Trace208 self, uint48 key, uint208 value) → uint208, uint208
internal
Pushes a (key
, value
) pair into a Trace208 so that it is stored as the checkpoint.
Returns previous value and new value.
Never accept key as a user input, since an arbitrary type(uint48).max key set will disable the
library.
|
lowerLookup(struct Checkpoints.Trace208 self, uint48 key) → uint208
internal
Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if there is none.
upperLookup(struct Checkpoints.Trace208 self, uint48 key) → uint208
internal
Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none.
upperLookupRecent(struct Checkpoints.Trace208 self, uint48 key) → uint208
internal
Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none.
This is a variant of upperLookup that is optimised to find "recent" checkpoint (checkpoints with high
keys).
|
latest(struct Checkpoints.Trace208 self) → uint208
internal
Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
latestCheckpoint(struct Checkpoints.Trace208 self) → bool exists, uint48 _key, uint208 _value
internal
Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value in the most recent checkpoint.
at(struct Checkpoints.Trace208 self, uint32 pos) → struct Checkpoints.Checkpoint208
internal
Returns checkpoint at given position.
push(struct Checkpoints.Trace160 self, uint96 key, uint160 value) → uint160, uint160
internal
Pushes a (key
, value
) pair into a Trace160 so that it is stored as the checkpoint.
Returns previous value and new value.
Never accept key as a user input, since an arbitrary type(uint96).max key set will disable the
library.
|
lowerLookup(struct Checkpoints.Trace160 self, uint96 key) → uint160
internal
Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if there is none.
upperLookup(struct Checkpoints.Trace160 self, uint96 key) → uint160
internal
Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none.
upperLookupRecent(struct Checkpoints.Trace160 self, uint96 key) → uint160
internal
Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none.
This is a variant of upperLookup that is optimised to find "recent" checkpoint (checkpoints with high
keys).
|
latest(struct Checkpoints.Trace160 self) → uint160
internal
Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
latestCheckpoint(struct Checkpoints.Trace160 self) → bool exists, uint96 _key, uint160 _value
internal
Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value in the most recent checkpoint.
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 addr
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 addr
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
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 or custom error, it is bubbled
up by this function (like regular Solidity function calls). However, if
the call reverted with no returned reason, this function reverts with a
FailedInnerCall
error.
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.
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
.
functionStaticCall(address target, bytes data) → bytes
internal
Same as functionCall
,
but performing a static call.
functionDelegateCall(address target, bytes data) → bytes
internal
Same as functionCall
,
but performing a delegate call.
verifyCallResultFromTarget(address target, bool success, bytes returndata) → bytes
internal
Tool to verify that a low level call to smart-contract was successful, and reverts if the target
was not a contract or bubbling up the revert reason (falling back to FailedInnerCall
) in case of an
unsuccessful call.
verifyCallResult(bool success, bytes returndata) → bytes
internal
Tool to verify that a low level call was successful, and reverts if it wasn’t, either by bubbling the
revert reason or with a default FailedInnerCall
error.
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.
unsafeAccess(address[] arr, uint256 pos) → struct StorageSlot.AddressSlot
internal
Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
Only use if you are certain pos is lower than the array length.
|
unsafeAccess(bytes32[] arr, uint256 pos) → struct StorageSlot.Bytes32Slot
internal
Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
Only use if you are certain pos is lower than the array length.
|
unsafeAccess(uint256[] arr, uint256 pos) → struct StorageSlot.Uint256Slot
internal
Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
Only use if you are certain pos is lower than the array length.
|
Base64
import "@openzeppelin/contracts/utils/Base64.sol";
Provides a set of functions to operate with Base64 strings.
Strings
import "@openzeppelin/contracts/utils/Strings.sol";
String operations.
toString(uint256 value) → string
internal
Converts a uint256
to its ASCII string
decimal representation.
toStringSigned(int256 value) → string
internal
Converts a int256
to its ASCII string
decimal representation.
toHexString(uint256 value) → string
internal
Converts a uint256
to its ASCII string
hexadecimal representation.
toHexString(uint256 value, uint256 length) → string
internal
Converts a uint256
to its ASCII string
hexadecimal representation with fixed length.
ShortStrings
import "@openzeppelin/contracts/utils/ShortStrings.sol";
This library provides functions to convert short memory strings
into a ShortString
type that can be used as an immutable variable.
Strings of arbitrary length can be optimized using this library if they are short enough (up to 31 bytes) by packing them with their length (1 byte) in a single EVM word (32 bytes). Additionally, a fallback mechanism can be used for every other case.
Usage example:
contract Named {
using ShortStrings for *;
ShortString private immutable _name;
string private _nameFallback;
constructor(string memory contractName) {
_name = contractName.toShortStringWithFallback(_nameFallback);
}
function name() external view returns (string memory) {
return _name.toStringWithFallback(_nameFallback);
}
}
toShortString(string str) → ShortString
internal
Encode a string of at most 31 chars into a ShortString
.
This will trigger a StringTooLong
error is the input string is too long.
toShortStringWithFallback(string value, string store) → ShortString
internal
Encode a string into a ShortString
, or write it to storage if it is too long.
toStringWithFallback(ShortString value, string store) → string
internal
Decode a string that was encoded to ShortString
or written to storage using {setWithFallback}.
byteLengthWithFallback(ShortString value, string store) → uint256
internal
Return the length of a string that was encoded to ShortString
or written to storage using
{setWithFallback}.
This will return the "byte length" of the string. This may not reflect the actual length in terms of actual characters as the UTF-8 encoding of a single character can span over multiple bytes. |
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(newImplementation.code.length > 0);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
}
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
.
getBytes32Slot(bytes32 slot) → struct StorageSlot.Bytes32Slot r
internal
Returns an Bytes32Slot
with member value
located at slot
.
getUint256Slot(bytes32 slot) → struct StorageSlot.Uint256Slot r
internal
Returns an Uint256Slot
with member value
located at slot
.
getStringSlot(bytes32 slot) → struct StorageSlot.StringSlot r
internal
Returns an StringSlot
with member value
located at slot
.
getStringSlot(string store) → struct StorageSlot.StringSlot r
internal
Returns an StringSlot
representation of the string storage pointer store
.
Multicall
import "@openzeppelin/contracts/utils/Multicall.sol";
Provides a function to batch together multiple calls in a single external call.
Consider any assumption about calldata validation performed by the sender may be violated if it’s not especially
careful about sending transactions invoking multicall
. For example, a relay address that filters function
selectors won’t filter calls nested within a multicall
operation.
Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. msg.sender is not {_msgSender}).
If a non-canonical context is identified, the following self delegatecall appends the last bytes of msg.data
to the subcall. This makes it safe to use with ERC2771Context . Contexts that don’t affect the resolution of
{_msgSender} are not propagated to subcalls.
|
Context
import "@openzeppelin/contracts/utils/Context.sol";
Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned).
This contract is only required for intermediate, library-like contracts.