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.
Security tools include:
-
Pausable
: provides a simple way to halt activity in your contracts (often in response to an external threat). -
ReentrancyGuard
: protects you from reentrant calls.
The Address
, Arrays
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.
For new data types:
-
Counters
: a simple way to get a counter that can only be incremented or decremented. 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.
Contracts
Pausable
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.
ReentrancyGuard
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 make it call a
private
function that does the actual work.
Libraries
Address
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,
|
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
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.
Counters
Provides counters that can only be incremented or decremented by one. 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;
Since it is not possible to overflow a 256 bit integer with increments of one, increment
can skip the SafeMath
overflow check, thereby saving gas. This does assume however correct usage, in that the underlying _value
is never
directly accessed.
Create2
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
.
EnumerableMap
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;
}
As of v3.0.0, only maps of type uint256 → address
(UintToAddressMap
) are
supported.
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 .
|
EnumerableSet
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
.
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
.
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
.
SafeCast
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.
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
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.