Utilities

Miscellaneous contracts and libraries containing utility functions you can use to improve security, work with new data types, or safely use low-level primitives.

Cryptography

ERC7739

import "@openzeppelin/community-contracts/utils/cryptography/ERC7739.sol";

Validates signatures wrapping the message hash in a nested EIP712 type. See ERC7739Utils.

Linking the signature to the EIP-712 domain separator is a security measure to prevent signature replay across different EIP-712 domains (e.g. a single offchain owner of multiple contracts).

This contract requires implementing the {_rawSignatureValidation} function, which passes the wrapped message hash, which may be either an typed data or a personal sign nested type.

EIP-712 uses ShortStrings to optimize gas costs for short strings (up to 31 characters). Consider that strings longer than that will use storage, which may limit the ability of the signer to be used within the ERC-4337 validation phase (due to ERC-7562 storage access rules).
Functions
  • isValidSignature(hash, signature)

EIP712
  • _domainSeparatorV4()

  • _hashTypedDataV4(structHash)

  • eip712Domain()

  • _EIP712Name()

  • _EIP712Version()

AbstractSigner
  • _rawSignatureValidation(hash, signature)

Events
IERC5267
  • EIP712DomainChanged()

isValidSignature(bytes32 hash, bytes signature) → bytes4 result public

Attempts validating the signature in a nested EIP-712 type.

A nested EIP-712 type might be presented in 2 different ways:

  • As a nested EIP-712 typed data

  • As a personal signature (an EIP-712 mimic of the eth_personalSign for a smart contract)

ERC7739Utils

import "@openzeppelin/community-contracts/utils/cryptography/ERC7739Utils.sol";

Utilities to process ERC-7739 typed data signatures that are specific to an EIP-712 domain.

This library provides methods to wrap, unwrap and operate over typed data signatures with a defensive rehashing mechanism that includes the application’s EIP-712 and preserves readability of the signed content using an EIP-712 nested approach.

A smart contract domain can validate a signature for a typed data structure in two ways:

A provider for a smart contract wallet would need to return this signature as the result of a call to personal_sign or eth_signTypedData, and this may be unsupported by API clients that expect a return value of 129 bytes, or specifically the r,s,v parameters of an ECDSA signature, as is for example specified for EIP-712.
Functions
  • encodeTypedDataSig(signature, appSeparator, contentsHash, contentsDescr)

  • decodeTypedDataSig(encodedSignature)

  • personalSignStructHash(contents)

  • typedDataSignStructHash(contentsName, contentsType, contentsHash, domainBytes)

  • typedDataSignStructHash(contentsDescr, contentsHash, domainBytes)

  • typedDataSignTypehash(contentsName, contentsType)

  • decodeContentsDescr(contentsDescr)

encodeTypedDataSig(bytes signature, bytes32 appSeparator, bytes32 contentsHash, string contentsDescr) → bytes internal

Nest a signature for a given EIP-712 type into a nested signature for the domain of the app.

Counterpart of decodeTypedDataSig to extract the original signature and the nested components.

decodeTypedDataSig(bytes encodedSignature) → bytes signature, bytes32 appSeparator, bytes32 contentsHash, string contentsDescr internal

Parses a nested signature into its components.

Constructed as follows:

signature ‖ APP_DOMAIN_SEPARATOR ‖ contentsHash ‖ contentsDescr ‖ uint16(contentsDescr.length)

  • signature is the signature for the (ERC-7739) nested struct hash. This signature indirectly signs over the original "contents" hash (from the app) and the account’s domain separator.

  • APP_DOMAIN_SEPARATOR is the EIP-712 {EIP712-_domainSeparatorV4} of the application smart contract that is requesting the signature verification (though ERC-1271).

  • contentsHash is the hash of the underlying data structure or message.

  • contentsDescr is a descriptor of the "contents" part of the the EIP-712 type of the nested signature.

This function returns empty if the input format is invalid instead of reverting. data instead.

personalSignStructHash(bytes32 contents) → bytes32 internal

Nests an ERC-191 digest into a PersonalSign EIP-712 struct, and returns the corresponding struct hash. This struct hash must be combined with a domain separator, using {MessageHashUtils-toTypedDataHash} before being verified/recovered.

This is used to simulates the personal_sign RPC method in the context of smart contracts.

typedDataSignStructHash(string contentsName, string contentsType, bytes32 contentsHash, bytes domainBytes) → bytes32 result internal

Nests an EIP-712 hash (contents) into a TypedDataSign EIP-712 struct, and returns the corresponding struct hash. This struct hash must be combined with a domain separator, using {MessageHashUtils-toTypedDataHash} before being verified/recovered.

typedDataSignStructHash(string contentsDescr, bytes32 contentsHash, bytes domainBytes) → bytes32 result internal

Variant of {typedDataSignStructHash-string-string-bytes32-bytes} that takes a content descriptor and decodes the contentsName and contentsType out of it.

typedDataSignTypehash(string contentsName, string contentsType) → bytes32 internal

Compute the EIP-712 typehash of the TypedDataSign structure for a given type (and typename).

decodeContentsDescr(string contentsDescr) → string contentsName, string contentsType internal

Parse the type name out of the ERC-7739 contents type description. Supports both the implicit and explicit modes.

Following ERC-7739 specifications, a contentsName is considered invalid if it’s empty or it contains any of the following bytes , )\x00

If the contentsType is invalid, this returns an empty string. Otherwise, the return string has non-zero length.

ZKEmailUtils

import "@openzeppelin/community-contracts/utils/cryptography/ZKEmailUtils.sol";

Library for ZKEmail signature validation utilities.

ZKEmail is a protocol that enables email-based authentication and authorization for smart contracts using zero-knowledge proofs. It allows users to prove ownership of an email address without revealing the email content or private keys.

The validation process involves several key components:

  • A DKIMRegistry (DomainKeys Identified Mail) verification mechanism to ensure the email was sent from a valid domain. Defined by an IDKIMRegistry interface.

  • A command template validation mechanism to ensure the email command matches the expected format and parameters.

  • A zero-knowledge proof verification mechanism to ensure the email was actually sent and received without revealing its contents. Defined by an IVerifier interface.

Functions
  • isValidZKEmail(emailAuthMsg, dkimregistry, verifier)

  • isValidZKEmail(emailAuthMsg, dkimregistry, verifier, template)

  • isValidZKEmail(emailAuthMsg, dkimregistry, verifier, template, stringCase)

isValidZKEmail(struct EmailAuthMsg emailAuthMsg, contract IDKIMRegistry dkimregistry, contract IVerifier verifier) → enum ZKEmailUtils.EmailProofError internal

Variant of isValidZKEmail that validates the ["signHash", "{uint}"] command template.

isValidZKEmail(struct EmailAuthMsg emailAuthMsg, contract IDKIMRegistry dkimregistry, contract IVerifier verifier, string[] template) → enum ZKEmailUtils.EmailProofError internal

Validates a ZKEmail authentication message.

This function takes an email authentication message, a DKIM registry contract, and a verifier contract as inputs. It performs several validation checks and returns a tuple containing a boolean success flag and an EmailProofError if validation failed. Returns {EmailProofError.NoError} if all validations pass, or false with a specific EmailProofError indicating which validation check failed.

Attempts to validate the command for all possible string Case values.

isValidZKEmail(struct EmailAuthMsg emailAuthMsg, contract IDKIMRegistry dkimregistry, contract IVerifier verifier, string[] template, enum ZKEmailUtils.Case stringCase) → enum ZKEmailUtils.EmailProofError internal

Variant of isValidZKEmail that validates a template with a specific string Case.

Useful for templates with Ethereum address matchers (i.e. {ethAddr}), which are case-sensitive (e.g., ["someCommand", "{address}"]).

Abstract Signers

AbstractSigner

import "@openzeppelin/community-contracts/utils/cryptography/AbstractSigner.sol";

Abstract contract for signature validation.

Developers must implement _rawSignatureValidation and use it as the lowest-level signature validation mechanism.

Functions
  • _rawSignatureValidation(hash, signature)

_rawSignatureValidation(bytes32 hash, bytes signature) → bool internal

Signature validation algorithm.

Implementing a signature validation algorithm is a security-sensitive operation as it involves cryptographic verification. It is important to review and test thoroughly before deployment. Consider using one of the signature verification libraries (ECDSA, P256 or RSA).

SignerECDSA

import "@openzeppelin/community-contracts/utils/cryptography/SignerECDSA.sol";

Implementation of AbstractSigner using ECDSA signatures.

For Account usage, a _setSigner function is provided to set the signer address. Doing so is easier for a factory, who is likely to use initializable clones of this contract.

Example of usage:

contract MyAccountECDSA is Account, SignerECDSA, Initializable {
    function initialize(address signerAddr) public initializer {
      _setSigner(signerAddr);
    }
}
Failing to call _setSigner either during construction (if used standalone) or during initialization (if used as a clone) may leave the signer either front-runnable or unusable.
Functions
  • _setSigner(signerAddr)

  • signer()

  • _rawSignatureValidation(hash, signature)

_setSigner(address signerAddr) internal

Sets the signer with the address of the native signer. This function should be called during construction or through an initializer.

signer() → address public

Return the signer’s address.

_rawSignatureValidation(bytes32 hash, bytes signature) → bool internal

Signature validation algorithm.

Implementing a signature validation algorithm is a security-sensitive operation as it involves cryptographic verification. It is important to review and test thoroughly before deployment. Consider using one of the signature verification libraries (ECDSA, P256 or RSA).

SignerERC7913

import "@openzeppelin/community-contracts/utils/cryptography/SignerERC7913.sol";

Implementation of AbstractSigner using ERC-7913 signature verification.

For Account usage, a _setSigner function is provided to set the ERC-7913 formatted signer. Doing so is easier for a factory, who is likely to use initializable clones of this contract.

The signer is a bytes object that concatenates a verifier address and a key: verifier || key.

Example of usage:

contract MyAccountERC7913 is Account, SignerERC7913, Initializable {
    function initialize(bytes memory signer_) public initializer {
      _setSigner(signer_);
    }
}
Failing to call _setSigner either during construction (if used standalone) or during initialization (if used as a clone) may leave the signer either front-runnable or unusable.
Functions
  • _setSigner(signer_)

  • signer()

  • _rawSignatureValidation(hash, signature)

_setSigner(bytes signer_) internal

Sets the signer (i.e. verifier || key) with an ERC-7913 formatted signer.

signer() → bytes public

Return the ERC-7913 signer (i.e. verifier || key).

_rawSignatureValidation(bytes32 hash, bytes signature) → bool internal

Verifies a signature using {ERC7913Utils.isValidSignatureNow} with signer, hash and signature.

SignerP256

import "@openzeppelin/community-contracts/utils/cryptography/SignerP256.sol";

Implementation of AbstractSigner using P256 signatures.

For Account usage, a _setSigner function is provided to set the signer public key. Doing so is easier for a factory, who is likely to use initializable clones of this contract.

Example of usage:

contract MyAccountP256 is Account, SignerP256, Initializable {
    function initialize(bytes32 qx, bytes32 qy) public initializer {
      _setSigner(qx, qy);
    }
}
Failing to call _setSigner either during construction (if used standalone) or during initialization (if used as a clone) may leave the signer either front-runnable or unusable.
Functions
  • _setSigner(qx, qy)

  • signer()

  • _rawSignatureValidation(hash, signature)

Errors
  • SignerP256InvalidPublicKey(qx, qy)

_setSigner(bytes32 qx, bytes32 qy) internal

Sets the signer with a P256 public key. This function should be called during construction or through an initializer.

signer() → bytes32 qx, bytes32 qy public

Return the signer’s P256 public key.

_rawSignatureValidation(bytes32 hash, bytes signature) → bool internal

Signature validation algorithm.

Implementing a signature validation algorithm is a security-sensitive operation as it involves cryptographic verification. It is important to review and test thoroughly before deployment. Consider using one of the signature verification libraries (ECDSA, P256 or RSA).

SignerP256InvalidPublicKey(bytes32 qx, bytes32 qy) error

SignerERC7702

import "@openzeppelin/community-contracts/utils/cryptography/SignerERC7702.sol";

Implementation of AbstractSigner for implementation for an EOA. Useful for ERC-7702 accounts.

Functions
  • _rawSignatureValidation(hash, signature)

_rawSignatureValidation(bytes32 hash, bytes signature) → bool internal

Validates the signature using the EOA’s address (i.e. address(this)).

SignerRSA

import "@openzeppelin/community-contracts/utils/cryptography/SignerRSA.sol";

Implementation of AbstractSigner using RSA signatures.

For Account usage, a _setSigner function is provided to set the signer public key. Doing so is easier for a factory, who is likely to use initializable clones of this contract.

Example of usage:

contract MyAccountRSA is Account, SignerRSA, Initializable {
    function initialize(bytes memory e, bytes memory n) public initializer {
      _setSigner(e, n);
    }
}
Failing to call _setSigner either during construction (if used standalone) or during initialization (if used as a clone) may leave the signer either front-runnable or unusable.
Functions
  • _setSigner(e, n)

  • signer()

  • _rawSignatureValidation(hash, signature)

_setSigner(bytes e, bytes n) internal

Sets the signer with a RSA public key. This function should be called during construction or through an initializer.

signer() → bytes e, bytes n public

Return the signer’s RSA public key.

_rawSignatureValidation(bytes32 hash, bytes signature) → bool internal

See AbstractSigner._rawSignatureValidation. Verifies a PKCSv1.5 signature by calling RSA.pkcs1Sha256.

Following the RSASSA-PKCS1-V1_5-VERIFY procedure outlined in RFC8017 (section 8.2.2), the provided hash is used as the M (message) and rehashed using SHA256 according to EMSA-PKCS1-v1_5 encoding as per section 9.2 (step 1) of the RFC.

SignerZKEmail

import "@openzeppelin/community-contracts/utils/cryptography/SignerZKEmail.sol";

Implementation of AbstractSigner using ZKEmail signatures.

ZKEmail enables secure authentication and authorization through email messages, leveraging DKIM signatures from a DKIMRegistry and zero-knowledge proofs enabled by a verifier contract that ensures email authenticity without revealing sensitive information. The DKIM registry is trusted to correctly update DKIM keys, but users can override this behaviour and set their own keys. This contract implements the core functionality for validating email-based signatures in smart contracts.

Developers must set the following components during contract initialization:

  • accountSalt - A unique identifier derived from the user’s email address and account code.

  • DKIMRegistry - An instance of the DKIM registry contract for domain verification.

  • verifier - An instance of the Verifier contract for zero-knowledge proof validation.

  • templateId - The template ID of the sign hash command, defining the expected format.

Example of usage:

contract MyAccountZKEmail is Account, SignerZKEmail, Initializable {
  function initialize(
      bytes32 accountSalt,
      IDKIMRegistry registry,
      IVerifier verifier,
      uint256 templateId
  ) public initializer {
      // Will revert if the signer is already initialized
      _setAccountSalt(accountSalt);
      _setDKIMRegistry(registry);
      _setVerifier(verifier);
      _setTemplateId(templateId);
  }
}
Avoiding to call _setAccountSalt, _setDKIMRegistry, _setVerifier and _setTemplateId either during construction (if used standalone) or during initialization (if used as a clone) may leave the signer either front-runnable or unusable.
Functions
  • accountSalt()

  • DKIMRegistry()

  • verifier()

  • templateId()

  • _setAccountSalt(accountSalt_)

  • _setDKIMRegistry(registry_)

  • _setVerifier(verifier_)

  • _setTemplateId(templateId_)

  • _rawSignatureValidation(hash, signature)

Errors
  • InvalidEmailProof(err)

accountSalt() → bytes32 public

Unique identifier for owner of this contract defined as a hash of an email address and an account code.

An account code is a random integer in a finite scalar field of BN254 curve. It is a private randomness to derive a CREATE2 salt of the user’s Ethereum address from the email address, i.e., userEtherAddr := CREATE2(hash(userEmailAddr, accountCode)).

The account salt is used for:

  • Privacy: Enables email address privacy on-chain so long as the randomly generated account code is not revealed to an adversary.

  • Security: Provides a unique identifier that cannot be easily guessed or brute-forced, as it’s derived from both the email address and a random account code.

  • Deterministic Address Generation: Enables the creation of deterministic addresses based on email addresses, allowing users to recover their accounts using only their email.

DKIMRegistry() → contract IDKIMRegistry public

An instance of the DKIM registry contract. See DKIM Verification.

verifier() → contract IVerifier public

An instance of the Verifier contract. See ZK Proofs.

templateId() → uint256 public

The command template of the sign hash command.

_setAccountSalt(bytes32 accountSalt_) internal

Set the accountSalt.

_setDKIMRegistry(contract IDKIMRegistry registry_) internal

Set the DKIMRegistry contract address.

_setVerifier(contract IVerifier verifier_) internal

Set the verifier contract address.

_setTemplateId(uint256 templateId_) internal

Set the command’s templateId.

_rawSignatureValidation(bytes32 hash, bytes signature) → bool internal

See AbstractSigner._rawSignatureValidation. Validates a raw signature by:

  1. Decoding the email authentication message from the signature

  2. Verifying the hash matches the command parameters

  3. Checking the template ID matches

  4. Validating the account salt

  5. Verifying the email proof

InvalidEmailProof(enum ZKEmailUtils.EmailProofError err) error

Proof verification error.

ERC-7913

ERC7913Utils

import "@openzeppelin/community-contracts/utils/cryptography/ERC7913Utils.sol";

Library that provides common ERC-7913 utility functions.

This library extends the functionality of SignatureChecker to support signature verification for keys that do not have an Ethereum address of their own as with ERC-1271.

See ERC-7913.

Functions
  • isValidSignatureNow(signer, hash, signature)

isValidSignatureNow(bytes signer, bytes32 hash, bytes signature) → bool internal

Verifies a signature for a given signer and hash.

The signer is a bytes object that is the concatenation of an address and optionally a key: verifier || key. A signer must be at least 20 bytes long.

Verification is done as follows: - If signer.length < 20: verification fails - If signer.length == 20: verification is done using {SignatureChecker} - Otherwise: verification is done using {IERC7913SignatureVerifier}

ERC7913SignatureVerifierP256

import "@openzeppelin/community-contracts/utils/cryptography/ERC7913SignatureVerifierP256.sol";

ERC-7913 signature verifier that support P256 (secp256r1) keys.

Functions
  • verify(key, hash, signature)

verify(bytes key, bytes32 hash, bytes signature) → bytes4 public

Verifies signature as a valid signature of hash by key.

MUST return the bytes4 magic value IERC7913SignatureVerifier.verify.selector if the signature is valid. SHOULD return 0xffffffff or revert if the signature is not valid. SHOULD return 0xffffffff or revert if the key is empty

ERC7913SignatureVerifierRSA

import "@openzeppelin/community-contracts/utils/cryptography/ERC7913SignatureVerifierRSA.sol";

ERC-7913 signature verifier that support RSA keys.

Functions
  • verify(key, hash, signature)

verify(bytes key, bytes32 hash, bytes signature) → bytes4 public

Verifies signature as a valid signature of hash by key.

MUST return the bytes4 magic value IERC7913SignatureVerifier.verify.selector if the signature is valid. SHOULD return 0xffffffff or revert if the signature is not valid. SHOULD return 0xffffffff or revert if the key is empty

Structs

EnumerableSetExtended

import "@openzeppelin/community-contracts/utils/structs/EnumerableSetExtended.sol";

Library for managing sets of non-value 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.

  • Set can be cleared (all elements removed) in O(n).

contract Example {
    // Add the library methods
    using EnumerableSetExtended for EnumerableSetExtended.StringSet;

    // Declare a set state variable
    EnumerableSetExtended.StringSet private mySet;
}

Sets of type string (StringSet), bytes (BytesSet) and bytes32[2] (Bytes32x2Set) 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.

This is an extension of openzeppelin/contracts/utils/struct/EnumerableSet.sol.
Functions
  • add(self, value)

  • remove(self, value)

  • clear(set)

  • contains(self, value)

  • length(self)

  • at(self, index)

  • values(self)

  • add(self, value)

  • remove(self, value)

  • clear(set)

  • contains(self, value)

  • length(self)

  • at(self, index)

  • values(self)

  • add(self, value)

  • remove(self, value)

  • clear(self)

  • contains(self, value)

  • length(self)

  • at(self, index)

  • values(self)

add(struct EnumerableSetExtended.StringSet self, string 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 EnumerableSetExtended.StringSet self, string 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.

clear(struct EnumerableSetExtended.StringSet set) internal

Removes all the values from a set. O(n).

Developers should keep in mind that this function has an unbounded cost and using it may render the function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.

contains(struct EnumerableSetExtended.StringSet self, string value) → bool internal

Returns true if the value is in the set. O(1).

length(struct EnumerableSetExtended.StringSet self) → uint256 internal

Returns the number of values on the set. O(1).

at(struct EnumerableSetExtended.StringSet self, uint256 index) → string 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 than length.

values(struct EnumerableSetExtended.StringSet self) → string[] 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 EnumerableSetExtended.BytesSet self, bytes 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 EnumerableSetExtended.BytesSet self, bytes 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.

clear(struct EnumerableSetExtended.BytesSet set) internal

Removes all the values from a set. O(n).

Developers should keep in mind that this function has an unbounded cost and using it may render the function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.

contains(struct EnumerableSetExtended.BytesSet self, bytes value) → bool internal

Returns true if the value is in the set. O(1).

length(struct EnumerableSetExtended.BytesSet self) → uint256 internal

Returns the number of values on the set. O(1).

at(struct EnumerableSetExtended.BytesSet self, uint256 index) → bytes 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 than length.

values(struct EnumerableSetExtended.BytesSet self) → bytes[] 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 EnumerableSetExtended.Bytes32x2Set self, bytes32[2] 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 EnumerableSetExtended.Bytes32x2Set self, bytes32[2] 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.

clear(struct EnumerableSetExtended.Bytes32x2Set self) internal

Removes all the values from a set. O(n).

Developers should keep in mind that this function has an unbounded cost and using it may render the function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.

contains(struct EnumerableSetExtended.Bytes32x2Set self, bytes32[2] value) → bool internal

Returns true if the value is in the set. O(1).

length(struct EnumerableSetExtended.Bytes32x2Set self) → uint256 internal

Returns the number of values on the set. O(1).

at(struct EnumerableSetExtended.Bytes32x2Set self, uint256 index) → bytes32[2] 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 than length.

values(struct EnumerableSetExtended.Bytes32x2Set self) → bytes32[2][] 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.

EnumerableMapExtended

import "@openzeppelin/community-contracts/utils/structs/EnumerableMapExtended.sol";

Library for managing an enumerable variant of Solidity’s mapping type for non-value types as keys.

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.

  • Map can be cleared (all entries removed) in O(n).

contract Example {
    // Add the library methods
    using EnumerableMapExtended for EnumerableMapExtended.BytesToUintMap;

    // Declare a set state variable
    EnumerableMapExtended.BytesToUintMap private myMap;
}

The following map types are supported:

  • bytes → uint256 (BytesToUintMap)

  • string → string (StringToStringMap)

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.

Extensions of openzeppelin/contracts/utils/struct/EnumerableMap.sol.
Functions
  • set(map, key, value)

  • remove(map, key)

  • clear(map)

  • contains(map, key)

  • length(map)

  • at(map, index)

  • tryGet(map, key)

  • get(map, key)

  • keys(map)

  • set(map, key, value)

  • remove(map, key)

  • clear(map)

  • contains(map, key)

  • length(map)

  • at(map, index)

  • tryGet(map, key)

  • get(map, key)

  • keys(map)

Errors
  • EnumerableMapNonexistentBytesKey(key)

  • EnumerableMapNonexistentStringKey(key)

set(struct EnumerableMapExtended.BytesToUintMap map, bytes 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 EnumerableMapExtended.BytesToUintMap map, bytes 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.

clear(struct EnumerableMapExtended.BytesToUintMap map) internal

Removes all the entries from a map. O(n).

Developers should keep in mind that this function has an unbounded cost and using it may render the function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.

contains(struct EnumerableMapExtended.BytesToUintMap map, bytes key) → bool internal

Returns true if the key is in the map. O(1).

length(struct EnumerableMapExtended.BytesToUintMap map) → uint256 internal

Returns the number of key-value pairs in the map. O(1).

at(struct EnumerableMapExtended.BytesToUintMap map, uint256 index) → bytes key, uint256 value 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 than length.

tryGet(struct EnumerableMapExtended.BytesToUintMap map, bytes key) → bool exists, uint256 value internal

Tries to returns the value associated with key. O(1). Does not revert if key is not in the map.

get(struct EnumerableMapExtended.BytesToUintMap map, bytes key) → uint256 value internal

Returns the value associated with key. O(1).

Requirements:

  • key must be in the map.

keys(struct EnumerableMapExtended.BytesToUintMap map) → bytes[] 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 EnumerableMapExtended.StringToStringMap map, string key, string 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 EnumerableMapExtended.StringToStringMap map, string 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.

clear(struct EnumerableMapExtended.StringToStringMap map) internal

Removes all the entries from a map. O(n).

Developers should keep in mind that this function has an unbounded cost and using it may render the function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.

contains(struct EnumerableMapExtended.StringToStringMap map, string key) → bool internal

Returns true if the key is in the map. O(1).

length(struct EnumerableMapExtended.StringToStringMap map) → uint256 internal

Returns the number of key-value pairs in the map. O(1).

at(struct EnumerableMapExtended.StringToStringMap map, uint256 index) → string key, string value 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 than length.

tryGet(struct EnumerableMapExtended.StringToStringMap map, string key) → bool exists, string value internal

Tries to returns the value associated with key. O(1). Does not revert if key is not in the map.

get(struct EnumerableMapExtended.StringToStringMap map, string key) → string value internal

Returns the value associated with key. O(1).

Requirements:

  • key must be in the map.

keys(struct EnumerableMapExtended.StringToStringMap map) → string[] 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.

EnumerableMapNonexistentBytesKey(bytes key) error

Query for a nonexistent map key.

EnumerableMapNonexistentStringKey(string key) error

Query for a nonexistent map key.

Libraries

Masks

import "@openzeppelin/community-contracts/utils/Masks.sol";

Library for handling bit masks

Functions
  • toMask(group)

  • toMask(groups)

  • get(self, group)

  • isEmpty(self)

  • complement(m1)

  • union(m1, m2)

  • intersection(m1, m2)

  • difference(m1, m2)

  • symmetricDifference(m1, m2)

toMask(uint8 group) → Masks.Mask internal

Returns a new mask with the bit at group index set to 1.

toMask(uint8[] groups) → Masks.Mask internal

Returns a new mask with the bits at groups indices set to 1.

get(Masks.Mask self, uint8 group) → bool internal

Get value of the mask at group index

isEmpty(Masks.Mask self) → bool internal

Whether the mask is bytes32(0)

complement(Masks.Mask m1) → Masks.Mask internal

Invert the bits of a mask

union(Masks.Mask m1, Masks.Mask m2) → Masks.Mask internal

Perform a bitwise OR operation on two masks

intersection(Masks.Mask m1, Masks.Mask m2) → Masks.Mask internal

Perform a bitwise AND operation on two masks

difference(Masks.Mask m1, Masks.Mask m2) → Masks.Mask internal

Perform a bitwise difference operation on two masks (m1 - m2)

symmetricDifference(Masks.Mask m1, Masks.Mask m2) → Masks.Mask internal

Returns the symmetric difference (∆) of two masks, also known as disjunctive union or exclusive OR (XOR)