ERC-20
| This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc20 |
This set of interfaces, contracts, and utilities are all related to the ERC-20 Token Standard.
| For an overview of ERC-20 tokens and a walk through on how to create a token contract read our ERC-20 guide. |
There are a few core contracts that implement the behavior specified in the ERC-20 standard:
-
IERC20: the interface all ERC-20 implementations should conform to. -
IERC20Metadata: the extended ERC-20 interface including thename,symbolanddecimalsfunctions. -
ERC20: the implementation of the ERC-20 interface, including thename,symbolanddecimalsoptional extensions to the standard interface.
Additionally there are multiple custom extensions, including:
-
ERC20Permit: gasless approval of tokens (standardized as ERC-2612). -
ERC3009: gasless transfer of tokens via signed authorizations (standardized as ERC-3009). -
ERC20TransferAuthorization: variant ofERC3009using keyed sequential nonces and supporting ERC-1271 signatures. -
ERC20Bridgeable: compatibility with crosschain bridges through ERC-7802. -
ERC20Burnable: destruction of own tokens. -
ERC20Capped: enforcement of a cap to the total supply when minting tokens. -
ERC20Crosschain: embeddedBridgeFungiblebridge, making the token crosschain through the use of ERC-7786 gateways. -
ERC20Pausable: ability to pause token transfers. -
ERC20FlashMint: token level support for flash loans through the minting and burning of ephemeral tokens (standardized as ERC-3156). -
ERC20Votes: support for voting and vote delegation. See the governance guide for a minimal example (with the required overrides when combining ERC20 + ERC20Permit + ERC20Votes). -
ERC20Wrapper: wrapper to create an ERC-20 backed by another ERC-20, with deposit and withdraw methods. Useful in conjunction withERC20Votes. -
ERC20TemporaryApproval: support for approvals lasting for only one transaction, as defined in ERC-7674. -
ERC1363: support for calling the target of a transfer or approval, enabling code execution on the receiver within a single transaction.
Some extensions are vault standards where shares are represented by the core ERC-20 functionality:
-
ERC4626: tokenized vault that manages shares (represented as ERC-20) that are backed by assets (another ERC-20). -
ERC7535: tokenized vault (extendingERC4626) whose underlying asset is the chain’s native asset (e.g. Ether) instead of an ERC-20. -
ERC7540: asynchronous tokenized vault (ERC-7540) with request-based deposit and/or redemption flows, completed by a fulfillment strategy for each side:-
ERC7540AdminDeposit,ERC7540AdminRedeem: requests are fulfilled by an admin at an admin-determined rate. -
ERC7540DelayDeposit,ERC7540DelayRedeem: requests become claimable after a configurable delay. -
ERC7540EpochDeposit,ERC7540EpochRedeem: requests submitted in the same epoch are fulfilled together at a single rate. -
ERC7540SyncDeposit,ERC7540SyncRedeem: the side behaves as a standard synchronous ERC-4626 flow.
-
Finally, there are some utilities to interact with ERC-20 contracts in various ways:
-
SafeERC20: a wrapper around the interface that eliminates the need to handle boolean return values.
Other utilities that support ERC-20 assets can be found in the codebase:
-
ERC-20 tokens can be timelocked (held for a beneficiary until a specified time) or vested (released following a given schedule) using a
VestingWallet.
This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC-20 (such as _mint) and expose them as external functions in the way they prefer.
|
Core
IERC20
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
Interface of the ERC-20 standard as defined in the ERC.
transfer(address to, uint256 value) → bool external
Moves a value amount of tokens from the caller’s account to to.
Returns a boolean value indicating whether the operation succeeded.
Emits a transfer event.
allowance(address owner, address spender) → uint256 external
Returns the remaining number of tokens that spender will be
allowed to spend on behalf of owner through transferFrom. This is
zero by default.
This value changes when approve or transferFrom are called.
approve(address spender, uint256 value) → bool external
Sets a value amount of tokens as the allowance of spender over the
caller’s tokens.
Returns a boolean value indicating whether the operation succeeded.
| Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender’s allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 |
Emits an Approval event.
transferFrom(address from, address to, uint256 value) → bool external
Moves a value amount of tokens from from to to using the
allowance mechanism. value is then deducted from the caller’s
allowance.
Returns a boolean value indicating whether the operation succeeded.
Emits a transfer event.
Transfer(address indexed from, address indexed to, uint256 value) event
Emitted when value tokens are moved from one account (from) to
another (to).
Note that value may be zero.
Approval(address indexed owner, address indexed spender, uint256 value) event
Emitted when the allowance of a spender for an owner is set by
a call to approve. value is the new allowance.
IERC20Metadata
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
Interface for the optional metadata functions from the ERC-20 standard.
ERC20
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
Implementation of the IERC20 interface.
This implementation is agnostic to the way tokens are created. This means
that a supply mechanism has to be added in a derived contract using _mint.
| For a detailed writeup see our guide How to implement supply mechanisms. |
The default value of decimals is 18. To change this, you should override
this function so it returns a different value.
We have followed general OpenZeppelin Contracts guidelines: functions revert
instead returning false on failure. This behavior is nonetheless
conventional and does not conflict with the expectations of ERC-20
applications.
constructor(string name_, string symbol_) internal
Both values are immutable: they can only be set once during construction.
decimals() → uint8 public
Returns the number of decimals used to get its user representation.
For example, if decimals equals 2, a balance of 505 tokens should
be displayed to a user as 5.05 (505 / 10 ** 2).
Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the default value returned by this function, unless it’s overridden.
This information is only used for display purposes: it in
no way affects any of the arithmetic of the contract, including
IERC20.balanceOf and IERC20.transfer.
|
transfer(address to, uint256 value) → bool public
See IERC20.transfer.
Requirements:
-
tocannot be the zero address. -
the caller must have a balance of at least
value.
allowance(address owner, address spender) → uint256 public
Returns the remaining number of tokens that spender will be
allowed to spend on behalf of owner through transferFrom. This is
zero by default.
This value changes when approve or transferFrom are called.
approve(address spender, uint256 value) → bool public
See IERC20.approve.
If value is the maximum uint256, the allowance is not updated on
transferFrom. This is semantically equivalent to an infinite approval.
|
Requirements:
-
spendercannot be the zero address.
transferFrom(address from, address to, uint256 value) → bool public
See IERC20.transferFrom.
Skips emitting an Approval event indicating an allowance update. This is not
required by the ERC. See _approve.
Does not update the allowance if the current allowance
is the maximum uint256.
|
Requirements:
-
fromandtocannot be the zero address. -
frommust have a balance of at leastvalue. -
the caller must have allowance for
from's tokens of at leastvalue.
_transfer(address from, address to, uint256 value) internal
Moves a value amount of tokens from from to to.
This internal function is equivalent to transfer, and can be used to
e.g. implement automatic token fees, slashing mechanisms, etc.
Emits a transfer event.
This function is not virtual, _update should be overridden instead.
|
_update(address from, address to, uint256 value) internal
Transfers a value amount of tokens from from to to, or alternatively mints (or burns) if from
(or to) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
this function.
Emits a transfer event.
_mint(address account, uint256 value) internal
Creates a value amount of tokens and assigns them to account, by transferring it from address(0).
Relies on the _update mechanism
Emits a transfer event with from set to the zero address.
This function is not virtual, _update should be overridden instead.
|
_burn(address account, uint256 value) internal
Destroys a value amount of tokens from account, lowering the total supply.
Relies on the _update mechanism.
Emits a transfer event with to set to the zero address.
This function is not virtual, _update should be overridden instead
|
_approve(address owner, address spender, uint256 value) internal
Sets value as the allowance of spender over the `owner’s tokens.
This internal function is equivalent to approve, and can be used to
e.g. set automatic allowances for certain subsystems, etc.
Emits an Approval event.
Requirements:
-
ownercannot be the zero address. -
spendercannot be the zero address.
Overrides to this logic should be done to the variant with an additional bool emitEvent argument.
_approve(address owner, address spender, uint256 value, bool emitEvent) internal
By default (when calling _approve) the flag is set to true. On the other hand, approval changes made by
_spendAllowance during the transferFrom operation sets the flag to false. This saves gas by not emitting any
Approval event during transferFrom operations.
Anyone who wishes to continue emitting Approval events on the transferFrom operation can force the flag to
true using the following override:
function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
super._approve(owner, spender, value, true);
}
Requirements are the same as _approve.
_spendAllowance(address owner, address spender, uint256 value) internal
Updates owner’s allowance for `spender based on spent value.
Does not update the allowance value in case of infinite allowance. Revert if not enough allowance is available.
Does not emit an Approval event.
Extensions
IERC20Permit
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in ERC-2612.
Adds the permit method, which can be used to change an account’s ERC-20 allowance (see IERC20.allowance) by
presenting a message signed by the account. By not relying on IERC20.approve, the token holder account doesn’t
need to send a transaction, and thus is not required to hold Ether at all.
Security Considerations
There are two important considerations concerning the use of permit. The first is that a valid permit signature
expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
considered as an intention to spend the allowance in any specific way. The second is that because permits have
built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
take this into consideration and allow a permit call to fail. Combining these two aspects, a pattern that may be
generally recommended is:
function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
doThing(..., value);
}
function doThing(..., uint256 value) public {
token.safeTransferFrom(msg.sender, address(this), value);
...
}
Observe that: 1) msg.sender is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
try/catch allows the permit to fail and makes the code tolerant to frontrunning. (See also
SafeERC20.safeTransferFrom).
Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so contracts should have entry points that don’t rely on permit.
permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external
Sets value as the allowance of spender over owner's tokens,
given owner's signed approval.
The same issues IERC20.approve has related to transaction
ordering also applies here.
|
Emits an Approval event.
Requirements:
-
spendercannot be the zero address. -
deadlinemust be a timestamp in the future. -
v,randsmust be a validsecp256k1signature fromownerover the EIP712-formatted function arguments. -
the signature must use
owner's current nonce (seenonces).
For more information on the signature format, see the relevant EIP section.
| See Security Considerations above. |
ERC20Permit
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in ERC-2612.
Adds the permit method, which can be used to change an account’s ERC-20 allowance (see IERC20.allowance) by
presenting a message signed by the account. By not relying on , the token holder account doesn’t
need to send a transaction, and thus is not required to hold Ether at all.IERC20.approve
constructor(string name) internal
Initializes the EIP712 domain separator using the name parameter, and setting version to "1".
It’s a good idea to use the same name that is defined as the ERC-20 token name.
permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public
Sets value as the allowance of spender over owner's tokens,
given owner's signed approval.
The same issues IERC20.approve has related to transaction
ordering also applies here.
|
Emits an Approval event.
Requirements:
-
spendercannot be the zero address. -
deadlinemust be a timestamp in the future. -
v,randsmust be a validsecp256k1signature fromownerover the EIP712-formatted function arguments. -
the signature must use
owner's current nonce (seenonces).
For more information on the signature format, see the relevant EIP section.
| See Security Considerations above. |
nonces(address owner) → uint256 public
Returns the current nonce for owner. This value must be
included whenever a signature is generated for permit.
Every successful call to permit increases owner's nonce by one. This
prevents a signature from being used multiple times.
ERC3009
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC3009.sol";
Implementation of the ERC-3009 Transfer With Authorization extension allowing transfers to be made via signatures, as defined in ERC-3009.
Adds the transferWithAuthorization and receiveWithAuthorization methods, which
can be used to change an account’s ERC-20 balance by presenting a message signed
by the account. By not relying on IERC20.approve and IERC20.transferFrom, the
token holder account doesn’t need to send a transaction, and thus is not required
to hold native currency (e.g. ETH) at all.
To enable both timestamp-based and block-number-based validity windows, validAfter and
validBefore use a dual-clock encoding mirroring ERC4337Utils. Bit 47 ({BLOCK_RANGE_FLAG}) acts as a
clock selector: when both validAfter and validBefore have this bit set, the values are interpreted
as block numbers; otherwise they are interpreted as Unix timestamps (the default, matching the ERC-3009
specification). Since the current clock fits in 48 bits, any bit set at position 47 or above (other than
the active clock-mode flag) makes the value point to an unreachable future. See _checkValidity.
|
authorizationState(address authorizer, bytes32 nonce) → bool public
Returns whether the nonce has been used by authorizer. A true value means the authorization
has already been consumed (either transferred or canceled) and can no longer be used; a false value
means the nonce is still available.
Nonces are randomly generated 32-byte values unique to the authorizer’s address.
transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) public
Executes a transfer with a signed authorization.
Requirements:
-
validAftermust be less than the current block timestamp. -
validBeforemust be greater than the current block timestamp. -
noncemust not have been used by thefromaccount. -
the signature must be valid for the authorization.
receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) public
Receives a transfer with a signed authorization from the payer.
Includes an additional check to ensure that the payee’s address (to) matches the caller
to prevent front-running attacks.
Requirements:
-
tomust be the caller of this function. -
validAftermust be less than the current block timestamp. -
validBeforemust be greater than the current block timestamp. -
noncemust not have been used by thefromaccount. -
the signature must be valid for the authorization.
cancelAuthorization(address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) public
Cancels an authorization.
Requirements:
-
noncemust not have been used by theauthorizeraccount. -
the signature must be valid for the cancellation.
_transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce) internal
Performs the time and nonce checks, then executes the transfer.
_cancelAuthorization(address authorizer, bytes32 nonce) internal
Consumes the nonce and emits the cancellation event.
_consumeNonce(address authorizer, bytes32 nonce) internal
Marks nonce as used for authorizer. Reverts with ERC3009UsedAuthorization if already consumed.
_checkValidity(uint256 validAfter, uint256 validBefore) internal
Checks the validity of the authorization against the current clock.
Following the ERC-4337-style dual-clock encoding, the clock is interpreted as block number only when
both validAfter and validBefore carry the {BLOCK_RANGE_FLAG}; otherwise it falls back to
timestamp (matching the ERC-3009 specification’s default). Mixed-flag inputs therefore fall back to
the timestamp clock rather than reverting, mirroring ERC4337Utils.parseValidationData. The flag bit
is masked off the values only when block-mode is engaged; in timestamp mode the full 256-bit value
participates in the comparison.
Any validAfter or validBefore with a bit set at position 47 or above (other than the active
clock-mode flag) is interpreted as an unreachable point in the future (i.e. never valid after or
always valid before, respectively).
|
ERC3009InvalidAuthorizationTime(uint256 validAfter, uint256 validBefore) error
The authorization is not valid at the given time
ERC20TransferAuthorization
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20TransferAuthorization.sol";
Variant of {ERC-3009} that uses keyed sequential nonces as defined in NoncesKeyed.
This extension uses keyed sequential nonces following the
ERC-4337 semi-abstracted nonce system.
The {bytes32} nonce field is interpreted as a 192-bit key packed with a 64-bit sequence. Nonces with
different keys are independent and can be submitted in parallel without ordering constraints, while nonces
sharing the same key must be used sequentially. This is unlike ERC20Permit which uses a single global
sequential nonce.
|
authorizationState(address authorizer, bytes32 nonce) → bool public
Returning false does not guarantee that the authorization is currently executable.
With keyed sequential nonces, a nonce may be blocked by a predecessor in the same key’s sequence
that has not yet been consumed.
|
transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, bytes signature) public
Same as transferWithAuthorization but with a bytes signature.
receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, bytes signature) public
Same as receiveWithAuthorization but with a bytes signature.
cancelAuthorization(address authorizer, bytes32 nonce, bytes signature) public
Same as cancelAuthorization but with a bytes signature.
| Due to the keyed sequential nonce model, only the next nonce in a given key’s sequence can be cancelled. It is not possible to directly cancel a future nonce whose predecessors in the same key have not yet been consumed or cancelled. To invalidate a future authorization, all preceding nonces in the same key must first be consumed or cancelled in order. |
_consumeNonce(address authorizer, bytes32 nonce) internal
Override the internal nonce consumption logic to use the keyed sequential nonces from NoncesKeyed.
This override does not call super._consumeNonce, so any sibling override added by another extension
is skipped under C3 linearization. Integrators combining this contract with extensions that introduce
additional side effects through _consumeNonce must reintroduce those side effects themselves.
|
ERC20Bridgeable
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Bridgeable.sol";
ERC20 extension that implements the standard token interface according to ERC-7802.
supportsInterface(bytes4 interfaceId) → bool public
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
ERC section
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
crosschainMint(address to, uint256 value) public
See IERC7802.CrosschainMint. Emits a IERC7802.CrosschainMint event.
crosschainBurn(address from, uint256 value) public
See IERC7802.CrosschainBurn. Emits a IERC7802.CrosschainBurn event.
_checkTokenBridge(address caller) internal
Checks if the caller is a trusted token bridge. MUST revert otherwise.
Developers should implement this function using an access control mechanism that allows
customizing the list of allowed senders. Consider using AccessControl or AccessManaged.
ERC20Burnable
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
Extension of ERC20 that allows token holders to destroy both their own
tokens and those that they have an allowance for, in a way that can be
recognized off-chain (via event analysis).
burnFrom(address account, uint256 value) public
Destroys a value amount of tokens from account, deducting from
the caller’s allowance.
See ERC20._burn and ERC20.allowance.
Requirements:
-
the caller must have allowance for
account’s tokens of at least `value.
ERC20Capped
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol";
Extension of ERC20 that adds a cap to the supply of tokens.
constructor(uint256 cap_) internal
Sets the value of the cap. This value is immutable, it can only be
set once during construction.
_update(address from, address to, uint256 value) internal
Transfers a value amount of tokens from from to to, or alternatively mints (or burns) if from
(or to) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
this function.
Emits a transfer event.
ERC20Crosschain
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Crosschain.sol";
Extension of ERC20 that makes it natively cross-chain using the ERC-7786 based BridgeFungible.
This extension makes the token compatible with counterparts on other chains, which can be:
* ERC20Crosschain instances,
* ERC20 instances that are bridged using BridgeERC20,
* ERC20Bridgeable instances that are bridged using BridgeERC7802.
It is mostly equivalent to inheriting from both ERC20Bridgeable and BridgeERC7802, and configuring them such
that:
* token (on the BridgeERC7802 side) is address(this),
* _checkTokenBridge (on the ERC20Bridgeable side) is implemented such that it only accepts self-calls.
ERC20Pausable
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol";
ERC-20 token with pausable token transfers, minting and burning.
Useful for scenarios such as preventing trades until the end of an evaluation period, or having an emergency switch for freezing all token transfers in the event of a large bug.
This contract does not include public pause and unpause functions. In
addition to inheriting this contract, you must define both functions, invoking the
Pausable._pause and Pausable._unpause internal functions, with appropriate
access control, e.g. using AccessControl or Ownable. Not doing so will
make the contract pause mechanism of the contract unreachable, and thus unusable.
|
_update(address from, address to, uint256 value) internal
See ERC20._update.
Requirements:
-
the contract must not be paused.
ERC20Votes
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
Extension of ERC-20 to support Compound-like voting and delegation. This version is more generic than Compound’s, and supports token supply up to 2208 - 1, while COMP is limited to 296 - 1.
| This contract does not provide interface compatibility with Compound’s COMP token. |
This extension keeps a history (checkpoints) of each account’s vote power. Vote power can be delegated either
by calling the Votes.delegate function directly, or by providing a signature to be used with Votes.delegateBySig. Voting
power can be queried through the public accessors Votes.getVotes and Votes.getPastVotes.
By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
_maxSupply() → uint256 internal
Maximum token supply. Defaults to type(uint208).max (2208 - 1).
This maximum is enforced in _update. It limits the total supply of the token, which is otherwise a uint256,
so that checkpoints can be stored in the Trace208 structure used by Votes. Increasing this value will not
remove the underlying limitation, and will cause _update to fail because of a math overflow in
Votes._transferVotingUnits. An override could be used to further restrict the total supply (to a lower value) if
additional logic requires it. When resolving override conflicts on this function, the minimum should be
returned.
_update(address from, address to, uint256 value) internal
Move voting power when tokens are transferred.
Emits a IVotes.DelegateVotesChanged event.
_getVotingUnits(address account) → uint256 internal
Returns the voting units of an account.
Overriding this function may compromise the internal vote accounting.
ERC20Votes assumes tokens map to voting units 1:1 and this is not easy to change.
|
ERC20Wrapper
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Wrapper.sol";
Extension of the ERC-20 token contract to support token wrapping.
Users can deposit and withdraw "underlying tokens" and receive a matching number of "wrapped tokens". This is useful
in conjunction with other modules. For example, combining this wrapping mechanism with ERC20Votes will allow the
wrapping of an existing "basic" ERC-20 into a governance token.
Any mechanism in which the underlying token changes the balanceOf of an account without an explicit transfer
may desynchronize this contract’s supply and its underlying balance. Please exercise caution when wrapping tokens that
may undercollateralize the wrapper (i.e. wrapper’s total supply is higher than its underlying balance). See _recover
for recovering value accrued to the wrapper.
|
decimals() → uint8 public
See IERC20Metadata. Uses Math.ternary for branchless selection, which evaluates both branches. This is safe
because the default ERC20.decimals is commonly a constant.
If a derived contract overrides super.decimals() to read from
storage, it should also override this function and use a conditional ternary instead.
|
underlying() → contract IERC20 public
Returns the address of the underlying ERC-20 token that is being wrapped.
depositFor(address account, uint256 value) → bool public
Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
withdrawTo(address account, uint256 value) → bool public
Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
ERC20FlashMint
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20FlashMint.sol";
Implementation of the ERC-3156 Flash loans extension, as defined in ERC-3156.
Adds the flashLoan method, which provides flash loan support at the token
level. By default there is no fee, but this can be changed by overriding flashFee.
When this extension is used along with the ERC20Capped or ERC20Votes extensions,
maxFlashLoan will not correctly reflect the maximum that can be flash minted. We recommend
overriding maxFlashLoan so that it correctly reflects the supply cap.
|
maxFlashLoan(address token) → uint256 public
Returns the maximum amount of tokens available for loan.
This function will not automatically detect any supply cap
added by other extensions, such as ERC20Capped. If necessary,
override this function to take a supply cap into account.
|
flashFee(address token, uint256 value) → uint256 public
Returns the fee applied when doing flash loans. This function calls
the _flashFee function which returns the fee applied when doing flash
loans.
_flashFee(address, uint256) → uint256 internal
Returns the fee applied when doing flash loans. By default this implementation has 0 fees. This function can be overridden to make the flash loan mechanism deflationary.
_flashFeeReceiver() → address internal
Returns the receiver address of the flash fee. By default this implementation returns the address(0) which means the fee amount will be burnt. This function can be overridden to change the fee receiver.
flashLoan(contract IERC3156FlashBorrower receiver, address token, uint256 value, bytes data) → bool public
Performs a flash loan. New tokens are minted and sent to the
receiver, who is required to implement the IERC3156FlashBorrower
interface. By the end of the flash loan, the receiver is expected to own
value + fee tokens and have them approved back to the token contract itself so
they can be burned.
ERC3156ExceededMaxLoan(uint256 maxLoan) error
The requested loan exceeds the max loan value for token.
ERC3156InvalidReceiver(address receiver) error
The receiver of a flashloan is not a valid IERC3156FlashBorrower.onFlashLoan implementer.
ERC20TemporaryApproval
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20TemporaryApproval.sol";
Extension of ERC20 that adds support for temporary allowances following ERC-7674.
| This is a draft contract. The corresponding ERC is still subject to changes. |
Available since v5.1.
allowance(address owner, address spender) → uint256 public
allowance override that includes the temporary allowance when looking up the current allowance. If
adding up the persistent and the temporary allowances result in an overflow, type(uint256).max is returned.
_temporaryAllowance(address owner, address spender) → uint256 internal
Internal getter for the current temporary allowance that spender has over owner tokens.
temporaryApprove(address spender, uint256 value) → bool public
Alternative to approve that sets a value amount of tokens as the temporary allowance of spender over
the caller’s tokens.
Returns a boolean value indicating whether the operation succeeded.
Requirements:
- spender cannot be the zero address.
Does NOT emit an Approval event.
_temporaryApprove(address owner, address spender, uint256 value) internal
Sets value as the temporary allowance of spender over the `owner’s tokens.
This internal function is equivalent to temporaryApprove, and can be used to e.g. set automatic allowances
for certain subsystems, etc.
Requirements:
- owner cannot be the zero address.
- spender cannot be the zero address.
Does NOT emit an Approval event.
_spendAllowance(address owner, address spender, uint256 value) internal
_spendAllowance override that consumes the temporary allowance (if any) before eventually falling back
to consuming the persistent allowance.
NOTE: This function skips calling super._spendAllowance if the temporary allowance
is enough to cover the spending.
ERC1363
import "@openzeppelin/contracts/token/ERC20/extensions/ERC1363.sol";
Extension of ERC20 tokens that adds support for code execution after transfers and approvals
on recipient contracts. Calls after transfers are enabled through the ERC1363.transferAndCall and
ERC1363.transferFromAndCall methods while calls after approvals can be made with ERC1363.approveAndCall
Available since v5.1.
supportsInterface(bytes4 interfaceId) → bool public
Returns true if this contract implements the interface defined by
interfaceId. See the corresponding
ERC section
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
transferAndCall(address to, uint256 value) → bool public
Moves a value amount of tokens from the caller’s account to to
and then calls IERC1363Receiver.onTransferReceived on to. Returns a flag that indicates
if the call succeeded.
Requirements:
-
The target has code (i.e. is a contract).
-
The target
tomust implement theIERC1363Receiverinterface. -
The target must return the
IERC1363Receiver.onTransferReceivedselector to accept the transfer. -
The internal
transfermust succeed (returnedtrue).
transferAndCall(address to, uint256 value, bytes data) → bool public
Variant of transferAndCall that accepts an additional data parameter with
no specified format.
transferFromAndCall(address from, address to, uint256 value) → bool public
Moves a value amount of tokens from from to to using the allowance mechanism
and then calls IERC1363Receiver.onTransferReceived on to. Returns a flag that indicates
if the call succeeded.
Requirements:
-
The target has code (i.e. is a contract).
-
The target
tomust implement theIERC1363Receiverinterface. -
The target must return the
IERC1363Receiver.onTransferReceivedselector to accept the transfer. -
The internal
transferFrommust succeed (returnedtrue).
transferFromAndCall(address from, address to, uint256 value, bytes data) → bool public
Variant of transferFromAndCall that accepts an additional data parameter with
no specified format.
approveAndCall(address spender, uint256 value) → bool public
Sets a value amount of tokens as the allowance of spender over the
caller’s tokens and then calls IERC1363Spender.onApprovalReceived on spender.
Returns a flag that indicates if the call succeeded.
Requirements:
-
The target has code (i.e. is a contract).
-
The target
spendermust implement theIERC1363Spenderinterface. -
The target must return the
IERC1363Spender.onApprovalReceivedselector to accept the approval. -
The internal
approvemust succeed (returnedtrue).
approveAndCall(address spender, uint256 value, bytes data) → bool public
Variant of approveAndCall that accepts an additional data parameter with
no specified format.
ERC1363TransferFailed(address receiver, uint256 value) error
Indicates a failure within the transfer part of a transferAndCall operation.
ERC1363TransferFromFailed(address sender, address receiver, uint256 value) error
Indicates a failure within the transferFrom part of a transferFromAndCall operation.
ERC1363ApproveFailed(address spender, uint256 value) error
Indicates a failure within the approve part of a approveAndCall operation.
Vaults
ERC4626
import "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in ERC-4626.
This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
underlying "assets" through standardized deposit, mint, redeem and burn workflows. This contract extends
the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
contract and not the "assets" token which is an independent contract.
|
In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by verifying the amount received is as expected, using a wrapper that performs these checks such as ERC4626Router. Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
The The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
To learn more, check out our ERC-4626 guide. |
|
When overriding this contract, some elements must be considered:
|
|
Any mechanism that mints shares without a corresponding increase in the vault’s assets (collateral) will alter the
exchange rate and may open the door to vulnerabilities. In particular, this contract
must NOT be combined with |
constructor(contract IERC20 asset_) internal
Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
decimals() → uint8 public
Decimals are computed by adding the decimal offset on top of the underlying asset’s decimals. This "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the asset has not been created yet), a default of 18 is used to represent the underlying asset’s decimals.
asset() → address public
Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
-
MUST be an ERC-20 token contract.
-
MUST NOT revert.
totalAssets() → uint256 public
Returns the total amount of the underlying asset that is “managed” by Vault.
-
SHOULD include any compounding that occurs from yield.
-
MUST be inclusive of any fees that are charged against assets in the Vault.
-
MUST NOT revert.
convertToShares(uint256 assets) → uint256 public
Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.
-
MUST NOT be inclusive of any fees that are charged against assets in the Vault.
-
MUST NOT show any variations depending on the caller.
-
MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
-
MUST NOT revert.
| This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and from. |
convertToAssets(uint256 shares) → uint256 public
Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.
-
MUST NOT be inclusive of any fees that are charged against assets in the Vault.
-
MUST NOT show any variations depending on the caller.
-
MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
-
MUST NOT revert.
| This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and from. |
maxDeposit(address) → uint256 public
Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver, through a deposit call.
-
MUST return a limited value if receiver is subject to some deposit limit.
-
MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
-
MUST NOT revert.
maxMint(address) → uint256 public
Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call. - MUST return a limited value if receiver is subject to some mint limit. - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted. - MUST NOT revert.
maxWithdraw(address owner) → uint256 public
Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the Vault, through a withdraw call.
-
MUST return a limited value if owner is subject to some withdrawal limit or timelock.
-
MUST NOT revert.
maxRedeem(address owner) → uint256 public
Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, through a redeem call.
-
MUST return a limited value if owner is subject to some withdrawal limit or timelock.
-
MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
-
MUST NOT revert.
previewDeposit(uint256 assets) → uint256 public
Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.
-
MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called in the same transaction.
-
MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the deposit would be accepted, regardless if the user has enough tokens approved, etc.
-
MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
-
MUST NOT revert.
| any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in share price or some other type of condition, meaning the depositor will lose assets by depositing. |
previewMint(uint256 shares) → uint256 public
Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions.
-
MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the same transaction.
-
MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint would be accepted, regardless if the user has enough tokens approved, etc.
-
MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
-
MUST NOT revert.
| any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in share price or some other type of condition, meaning the depositor will lose assets by minting. |
previewWithdraw(uint256 assets) → uint256 public
Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.
-
MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if called in the same transaction.
-
MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though the withdrawal would be accepted, regardless if the user has enough shares, etc.
-
MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
-
MUST NOT revert.
| any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in share price or some other type of condition, meaning the depositor will lose assets by depositing. |
previewRedeem(uint256 shares) → uint256 public
Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block, given current on-chain conditions.
-
MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the same transaction.
-
MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the redemption would be accepted, regardless if the user has enough shares, etc.
-
MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
-
MUST NOT revert.
| any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in share price or some other type of condition, meaning the depositor will lose assets by redeeming. |
deposit(uint256 assets, address receiver) → uint256 public
Deposit assets underlying tokens and send the corresponding number of vault shares (shares) to receiver.
-
MUST emit the Deposit event.
-
MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the deposit execution, and are accounted for during deposit.
-
MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not approving enough underlying tokens to the Vault contract, etc).
| most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. |
This function is payable to support vaults whose underlying is the chain’s native asset (see
ERC7535). Vaults over an ERC-20 underlying do not expect a native value and should reject a non-zero
msg.value.
|
mint(uint256 shares, address receiver) → uint256 public
Mints exactly shares vault shares to receiver in exchange for assets underlying tokens.
-
MUST emit the Deposit event.
-
MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint execution, and are accounted for during mint.
-
MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not approving enough underlying tokens to the Vault contract, etc).
| most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. |
This function is payable to support vaults whose underlying is the chain’s native asset (see
ERC7535). Vaults over an ERC-20 underlying do not expect a native value and should reject a non-zero
msg.value.
|
withdraw(uint256 assets, address receiver, address owner) → uint256 public
Burns shares from owner and sends exactly assets of underlying tokens to receiver.
-
MUST emit the Withdraw event.
-
MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the withdraw execution, and are accounted for during withdraw.
-
MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner not having enough shares, etc).
Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. Those methods should be performed separately.
redeem(uint256 shares, address receiver, address owner) → uint256 public
Burns exactly shares from owner and sends assets of underlying tokens to receiver.
-
MUST emit the Withdraw event.
-
MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the redeem execution, and are accounted for during redeem.
-
MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner not having enough shares, etc).
| some implementations will require pre-requesting to the Vault before a withdrawal may be performed. Those methods should be performed separately. |
_convertToShares(uint256 assets, enum Math.Rounding rounding) → uint256 internal
Internal conversion function (from assets to shares) with support for rounding direction.
_convertToAssets(uint256 shares, enum Math.Rounding rounding) → uint256 internal
Internal conversion function (from shares to assets) with support for rounding direction.
_deposit(address caller, address receiver, uint256 assets, uint256 shares) internal
Deposit/mint common workflow.
_withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares) internal
Withdraw/redeem common workflow.
_transferIn(address from, uint256 assets) internal
Performs a transfer in of underlying assets. The default implementation uses SafeERC20. Used by _deposit.
_transferOut(address to, uint256 assets) internal
Performs a transfer out of underlying assets. The default implementation uses SafeERC20. Used by _withdraw.
_enablePayableDeposit() → bool internal
deposit and mint are payable so that vaults whose underlying is the chain’s native asset (see
ERC7535) can receive it as msg.value. The default implementation, used by ERC-4626 vaults, returns
false so that any native value sent is rejected, which preserves the behavior of a non-payable entry
point. Native asset vaults override this to return true and process msg.value themselves.
_decimalsOffset() → uint8 internal
Offset between the decimals of the underlying asset and those of the vault shares. See the contract-level documentation on inflation attacks.
The conversion math computes 10 ** _decimalsOffset(), which overflows from an offset of 78 onwards.
Overrides must return at most 77, otherwise every deposit, mint, preview and conversion reverts.
|
ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max) error
Attempted to deposit more assets than the max amount for receiver.
ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max) error
Attempted to mint more shares than the max amount for receiver.
ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max) error
Attempted to withdraw more assets than the max amount for owner.
ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max) error
Attempted to redeem more shares than the max amount for owner.
ERC4626UnexpectedNativeValue(uint256 value) error
Attempted to deposit or mint with a native value (msg.value) the vault does not expect. The
vault reverts with this error on any non-zero msg.value unless _enablePayableDeposit is overridden to
return true, as native-asset vaults (see ERC7535) do.
ERC7535
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7535.sol";
Implementation of the ERC-7535 "Native Asset ERC-4626 Tokenized Vault" as defined in ERC-7535.
ERC-7535 is an adaptation of ERC4626 that uses the chain’s native asset (e.g. Ether) as the underlying
asset instead of an ERC-20 token. It is implemented as a thin extension of ERC4626: the share accounting,
rounding directions, virtual-offset inflation mitigation, preview functions, and checks-effects-interactions
ordering are all inherited unchanged.
Relative to ERC4626:
-
assetreturns the ERC-7528 native-asset placeholder0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE. -
totalAssetsreturns the contract’s own native-asset balance (address(this).balance), excluding themsg.valueof the current call. Shares are therefore priced against the pre-deposit balance, as inERC4626. -
depositandmintarepayable(as declared byIERC4626): the native asset is provided asmsg.valuerather than pulled with an ERC-20transferFrom, so there is no allowance flow for the underlying.depositprices shares offmsg.valueand ignores itsassetsargument (per ERC-7535);mintrequiresmsg.valueto cover the previewed cost.ERC4626._enablePayableDepositis overridden to accept the native value. -
ERC4626._transferInis a no-op (the value has already arrived asmsg.value) andERC4626._transferOutsends the native asset out withAddress.sendValue.
A vault backed by a wrapped native asset (such as WETH9) MUST NOT use this contract; per ERC-7528
and ERC-7535 such a vault is a plain ERC4626 over the wrapper ERC-20 and MUST report that wrapper’s address
from asset, not the native-asset placeholder.
|
|
Like A native asset vault can additionally be force-fed value (e.g. through |
deposit(assets, receiver) deposits the entire msg.value and mints previewDeposit(msg.value) shares,
ignoring the assets argument (per ERC-7535). mint(shares, receiver) requires msg.value to be at least the
previewed cost; any excess msg.value on a mint is refunded to the caller.
|
deposit and mint rely on msg.value, which is preserved across a delegatecall. A payable
batching mechanism that delegatecall`s into the vault itself would let the same `msg.value be counted by every
deposit or mint in the batch, minting shares several times for a single payment. Multicall is safe in
this regard because Multicall.multicall is not payable (msg.value is always zero in its subcalls), but it
MUST NOT be replaced by a payable variant.
|
To learn more, check out our ERC-7535 guide.
totalAssets() → uint256 public
Excludes the msg.value of the current call, so that deposit and mint price shares against the
pre-deposit balance (and a standalone previewDeposit matches the subsequent deposit). Outside a payable
call, msg.value is 0 and this is the full balance.
When extending this contract, consider that native asset sent out during a payable call, such as
the refund of an overpaid mint, is still subtracted through msg.value. For the rest of that call,
totalAssets returns a value lowered by the amount sent, and reverts if that amount exceeds the pre-deposit
balance.
|
deposit(uint256, address receiver) → uint256 public
Per ERC-7535, the deposited amount is the entire msg.value: shares are priced off msg.value and the
assets argument is ignored, so the full native value sent is always converted to shares (none is silently
retained as a donation). Reverts via maxDeposit if msg.value exceeds the maximum.
mint(uint256 shares, address receiver) → uint256 public
Reverts with ERC7535InsufficientNativeValue if msg.value is below the returned assets, and refunds
any excess to the caller through _refund. The refund runs after _deposit returns, so a _deposit override
sees the pre-deposit totalAssets, and a reentrant call during the refund sees a totalAssets and
totalSupply that both account for this deposit.
_enablePayableDeposit() → bool internal
See ERC4626._enablePayableDeposit. Native value is processed by the deposit and mint overrides.
_transferIn(address, uint256) internal
No-op: the native asset has already been received as msg.value. See ERC4626._transferIn.
_transferOut(address to, uint256 assets) internal
Sends the native asset out with Address.sendValue, which forwards all remaining gas. See
ERC4626._transferOut.
_refund(address to, uint256 value) internal
Sends back native value that was received but never became vault assets, such as the excess
msg.value of a mint. Kept separate from _transferOut so that custom payout logic (e.g. unstaking
assets before sending them) does not apply to refunds. Uses Address.sendValue, which forwards all
remaining gas.
ERC7535InsufficientNativeValue(uint256 value, uint256 expected) error
Attempted to mint with a msg.value below the previewed cost of the shares.
ERC7540
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540.sol";
Implementation of the ERC-7540 "Asynchronous ERC-4626 Tokenized Vaults" as defined in ERC-7540.
This abstract contract provides a single base for building vaults with asynchronous deposit and/or redemption
flows on top of ERC-4626. It integrates operator management (IERC7540Operator), the full ERC-4626 vault
interface, and routing logic that delegates to either synchronous (standard ERC-4626) or asynchronous paths
depending on the return value of _isDepositAsync and _isRedeemAsync.
Subcontracts choose their async behavior by overriding two internal pure boolean selectors:
-
_isDepositAsync: whentrue, the deposit side uses the Request lifecycle (Pending → Claimable → Claimed). -
_isRedeemAsync: whentrue, the redeem side uses the Request lifecycle.
Each async path requires a fulfillment strategy that implements the virtual hooks declared in this contract
(e.g. _consumeClaimableDeposit, _pendingDepositRequest, _asyncMaxDeposit, etc.).
Deposit and redeem strategies are independent: a vault can combine any deposit strategy with any redeem strategy (e.g. delay-based deposits with admin-based redeems).
Share custody during the async lifecycle is configurable via _depositShareOrigin and
_redeemShareDestination. When these return address(0) (the default), shares are minted/burned
at claim time. When they return a non-zero address, shares are pre-minted to (or transferred to)
that address at fulfillment time and then transferred to the receiver on claim.
|
When implementing a custom fulfillment strategy, the following virtual hooks MUST be overridden for each async side enabled:
The |
|
ERC-7540 introduces operator permissions that allow operators to manage requests on behalf of controllers. An operator approved by a controller can request deposits using the controller’s assets, request redemptions using the controller’s shares, and claim assets or shares on behalf of the controller. Users should only approve operators they fully trust with both their assets and shares. |
|
This contract assumes the underlying |
onlyOperatorOrController(bool async, address controller, address operator) modifier
Modifier that enforces operator-or-controller authorization.
When async is false the check is skipped, which allows the standard ERC-4626 flow where
msg.sender is the caller and no controller/operator distinction exists.
constructor(contract IERC20 asset_) internal
Sets the underlying asset contract. This must be an ERC-20-compatible contract.
Caches the asset’s decimals() value at construction time. If the call fails (e.g. the asset has not
been created yet), a default of 18 is used.
Requirements:
-
At least one of
_isDepositAsyncor_isRedeemAsyncmust returntrue.
Either _isDepositAsync or _isRedeemAsync must return true. Use ERC4626 otherwise.
|
supportsInterface(bytes4 interfaceId) → bool public
Reports support for IERC7540Operator unconditionally. Support for IERC7540Deposit and
IERC7540Redeem is conditional on the corresponding async selector returning true.
isOperator(address controller, address operator) → bool status public
Returns true if the operator is approved as an operator for a controller.
setOperator(address operator, bool approved) → bool public
Grants or revokes permissions for operator to manage requests on behalf of the caller.
-
MUST set the operator status to the
approvedvalue. -
MUST emit the {OperatorSet} event when the operator status is set.
-
MUST return true.
_setOperator(address controller, address operator, bool approved) internal
Sets the operator approval status for controller to approved.
Requirements:
-
operatormust not be thecontroller. A controller always has unrestricted access to its own tokens and requests, and that access cannot be revoked.
Emits an IERC7540Operator.OperatorSet event.
_checkOperatorOrController(bool async, address controller, address operator) internal
Reverts with ERC7540InvalidOperator if operator is not the controller and is not
approved as an operator for controller. When async is false the check is a no-op,
preserving standard ERC-4626 authorization semantics.
decimals() → uint8 public
Decimals are computed by adding the decimal offset on top of the underlying asset’s decimals. This "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the asset has not been created yet), a default of 18 is used to represent the underlying asset’s decimals.
asset() → address public
Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
-
MUST be an ERC-20 token contract.
-
MUST NOT revert.
totalAssets() → uint256 public
See IERC4626.totalAssets.
Pending deposit assets are subtracted from the vault’s token balance, since they have not yet been
converted into shares and must not be treated as yield for outstanding shareholders. Requests that
were fulfilled at a locked rate but not yet claimed are accounted as settled: the assets of Claimable
deposits (_totalClaimableDepositAssets) are added back, and the assets owed to Claimable redeems
(_totalClaimableRedeemAssets) are subtracted.
Internal flows preserve the invariant balanceOf(asset, vault) + _totalClaimableDepositAssets() >=
totalPendingDepositAssets() + _totalClaimableRedeemAssets() for any well-behaved ERC-20 (see
_isSolvent). Assets with transfer fees, negative rebases, or externally-mutable balances can violate
it and cause this function to revert with an underflow. Strategies that read totalAssets on the claim
path become uncallable in that state.
|
_isSolvent() → bool internal
Returns whether the vault’s asset balance covers the assets of pending deposits and the assets owed
to Claimable redeems, i.e. whether totalAssets does not underflow.
Checked by strategies after fulfilling redeem Requests at a locked rate, which revert with
ERC7540InsufficientAssets if it returns false, so that a fulfillment promising more assets than the vault
holds reverts instead of breaking totalAssets for the whole vault. Fulfillers must fund the vault before
fulfilling.
Vaults that override totalAssets to account for assets held outside the vault (e.g. deployed in a
strategy) should override this function accordingly.
|
_totalOutstandingShares() → uint256 internal
Total number of shares backing totalAssets, used by the vault’s conversions in place of
totalSupply.
Adds totalPendingRedeemShares to the ERC-20 supply. When shares are burned at request time
(i.e. _redeemShareDestination returns address(0)), pending redeem shares are removed from
the on-chain supply but still logically outstanding until fulfilled; this function compensates.
Requests that were fulfilled at a locked rate but not yet claimed are accounted as settled: shares
owed to Claimable deposits (_totalClaimableDepositShares) are added, and shares of Claimable
redeems (_totalClaimableRedeemShares) are subtracted.
totalSupply is left unchanged and always equals the sum of all ERC-20 balances, so it can
differ from this value while requests are in flight. Integrators pricing shares should use
convertToAssets rather than totalAssets() / totalSupply().
|
pendingDepositRequest(uint256 requestId, address controller) → uint256 public
Requirements:
-
_isDepositAsyncmust returntrue.
claimableDepositRequest(uint256 requestId, address controller) → uint256 public
Requirements:
-
_isDepositAsyncmust returntrue.
pendingRedeemRequest(uint256 requestId, address controller) → uint256 public
Requirements:
-
_isRedeemAsyncmust returntrue.
claimableRedeemRequest(uint256 requestId, address controller) → uint256 public
Requirements:
-
_isRedeemAsyncmust returntrue.
totalPendingDepositAssets() → uint256 public
Returns the total amount of underlying assets currently pending in deposit Requests.
totalPendingRedeemShares() → uint256 public
Returns the total amount of vault shares currently pending in redeem Requests.
convertToShares(uint256 assets) → uint256 public
Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.
-
MUST NOT be inclusive of any fees that are charged against assets in the Vault.
-
MUST NOT show any variations depending on the caller.
-
MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
-
MUST NOT revert.
| This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and from. |
convertToAssets(uint256 shares) → uint256 public
Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.
-
MUST NOT be inclusive of any fees that are charged against assets in the Vault.
-
MUST NOT show any variations depending on the caller.
-
MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
-
MUST NOT revert.
| This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and from. |
maxDeposit(address owner) → uint256 public
See IERC4626.maxDeposit.
When the deposit flow is synchronous, returns type(uint256).max (no vault-imposed limit).
When async, delegates to _asyncMaxDeposit which must be provided by the fulfillment strategy.
maxMint(address owner) → uint256 public
See IERC4626.maxMint.
When the deposit flow is synchronous, returns type(uint256).max.
When async, delegates to _asyncMaxMint.
maxWithdraw(address owner) → uint256 public
See IERC4626.maxWithdraw.
When the redeem flow is synchronous, returns the asset-equivalent of the owner’s share balance.
When async, delegates to _asyncMaxWithdraw.
maxRedeem(address owner) → uint256 public
See IERC4626.maxRedeem.
When the redeem flow is synchronous, returns the owner’s share balance.
When async, delegates to _asyncMaxRedeem.
previewDeposit(uint256 assets) → uint256 public
MUST revert when _isDepositAsync returns true, per the ERC-7540 specification which
mandates that preview functions revert for async flows.
previewMint(uint256 shares) → uint256 public
See IERC4626.previewMint.
MUST revert when _isDepositAsync returns true.
previewWithdraw(uint256 assets) → uint256 public
MUST revert when _isRedeemAsync returns true.
previewRedeem(uint256 shares) → uint256 public
MUST revert when _isRedeemAsync returns true.
requestDeposit(uint256 assets, address controller, address owner) → uint256 public
Transfers assets from owner into the vault and submits a deposit Request for controller.
The Request enters Pending state, with the requestId returned by _getDepositRequestId.
Requirements:
-
_isDepositAsyncmust returntrue. -
ownermust bemsg.senderormsg.sendermust be an approved operator ofowner. -
ownermust have approved the vault for at leastassetsof the underlying token.
The controller is the only address authorized to claim the resulting Request. Passing an address
with no claim authority (e.g. address(0), 0x…dead) or any contract that cannot itself call
deposit/mint or designate an operator via setOperator will permanently lock the committed
assets, since claims are gated by onlyOperatorOrController on controller and there is no
cancellation path. Callers are responsible for supplying a controller capable of authorizing claims.
|
deposit(uint256 assets, address receiver) → uint256 public
See IERC4626.Deposit. Calls the three-argument overload with msg.sender as controller.
This function is payable as declared by IERC4626, but rejects any native value.
|
deposit(uint256 assets, address receiver, address controller) → uint256 public
When async, claims assets worth of shares from a Claimable deposit Request controlled by controller,
and transfers the resulting shares to receiver. When sync, behaves as standard ERC-4626 deposit.
When _isDepositAsync is false, the controller parameter is ignored and receiver is used
for limit checks, matching standard ERC-4626 semantics.
|
Requirements:
-
assetsmust not exceedmaxDepositfor the relevant account. -
When async,
msg.sendermust becontrolleror an approved operator ofcontroller.
mint(uint256 shares, address receiver) → uint256 public
See IERC4626.mint. Calls the three-argument overload with msg.sender as controller.
This function is payable as declared by IERC4626, but rejects any native value.
|
mint(uint256 shares, address receiver, address controller) → uint256 public
See IERC7540Deposit.mint.
When async, claims exactly shares from a Claimable deposit Request controlled by controller,
and transfers them to receiver. When sync, behaves as standard ERC-4626 mint.
When _isDepositAsync is false, the controller parameter is ignored.
|
Requirements:
-
sharesmust not exceedmaxMintfor the relevant account. -
When async,
msg.sendermust becontrolleror an approved operator ofcontroller.
requestRedeem(uint256 shares, address controller, address owner) → uint256 public
Assumes control of shares from owner and submits a redeem Request for controller.
The Request enters Pending state, with the requestId returned by _getRedeemRequestId.
Authorization for a msg.sender not equal to owner may come from either ERC-20 approval
over the shares of owner or from operator approval (see IERC7540Operator). This is
consistent with the approach described in ERC-6909.
Requirements:
-
_isRedeemAsyncmust returntrue.
The controller is the only address authorized to claim the resulting Request. Passing an address
with no claim authority (e.g. address(0), 0x…dead) or any contract that cannot itself call
withdraw/redeem or designate an operator via setOperator will permanently lock the committed
shares, since claims are gated by onlyOperatorOrController on controller and there is no
cancellation path. Callers are responsible for supplying a controller capable of authorizing claims.
|
withdraw(uint256 assets, address receiver, address ownerOrController) → uint256 public
See IERC4626.Withdraw.
When async, claims assets from a Claimable redeem Request controlled by ownerOrController,
and transfers the underlying assets to receiver. When sync, behaves as standard ERC-4626 withdraw.
Per ERC-7540, when async the ownerOrController parameter acts as the controller
(replacing the traditional ERC-4626 owner role).
|
Requirements:
-
assetsmust not exceedmaxWithdrawforownerOrController. -
When async,
msg.sendermust beownerOrControlleror an approved operator. -
When sync,
msg.sendermust beownerOrControlleror have sufficient ERC-20 allowance.
redeem(uint256 shares, address receiver, address ownerOrController) → uint256 public
See IERC4626.redeem.
When async, claims shares from a Claimable redeem Request controlled by ownerOrController,
and transfers the corresponding underlying assets to receiver. When sync, behaves as standard
ERC-4626 redeem.
Per ERC-7540, when async the ownerOrController parameter acts as the controller.
|
Requirements:
-
sharesmust not exceedmaxRedeemforownerOrController. -
When async,
msg.sendermust beownerOrControlleror an approved operator. -
When sync,
msg.sendermust beownerOrControlleror have sufficient ERC-20 allowance.
_convertToShares(uint256 assets, enum Math.Rounding rounding) → uint256 internal
Internal conversion function (from assets to shares) with support for rounding direction.
Uses virtual shares and virtual assets to mitigate the inflation attack vector described in
ERC-4626 security considerations.
The offset is configurable via _decimalsOffset.
_convertToAssets(uint256 shares, enum Math.Rounding rounding) → uint256 internal
Internal conversion function (from shares to assets) with support for rounding direction.
_requestDeposit(uint256 assets, address controller, address owner, uint256 requestId) internal
Internal handler for deposit Requests. Increments totalPendingDepositAssets, transfers
assets from owner into the vault, and emits IERC7540Deposit.DepositRequest. requestDeposit uses
the requestId returned by _getDepositRequestId.
Strategies that track Requests separately (e.g. ERC7540DelayDeposit, ERC7540EpochDeposit) record the
Request under requestId. Other callers of this function are expected to pass the value returned by
_getDepositRequestId, so that the Request is recorded under the current maturity timepoint or epoch.
|
Strategy extensions (e.g. ERC7540AdminDeposit) should override this to record per-controller
pending state after calling super._requestDeposit(…).
totalPendingDepositAssets is incremented after _transferIn so that totalAssets stays
consistent if the asset has a pre-transfer hook (e.g. ERC-777 tokensToSend). Incrementing it before
the transfer would let such a hook observe the new liability without the matching balance, and claim
against a depressed totalAssets at an inflated rate.
|
Requirements:
-
_isDepositAsyncmust returntrue, otherwise reverts withERC7540SyncDeposit.
_mintSharesOnDepositFulfill(uint256 assets, uint256 shares) internal
Mints shares to _depositShareOrigin as part of deposit fulfillment when using the
pre-mint share custody model. Decrements totalPendingDepositAssets by assets.
This function requires _depositShareOrigin to return a non-zero address.
When _depositShareOrigin returns address(0), shares are minted directly at claim time
inside _deposit and this function must not be called.
|
_deposit(address callerOrController, address receiver, uint256 assets, uint256 shares) internal
Common workflow for deposit and mint claim operations.
Handles three cases depending on the vault configuration:
-
Synchronous (
_isDepositAsyncreturnsfalse): transfers assets fromcallerOrControllerinto the vault and mints new shares toreceiver. Standard ERC-4626 behavior. -
Async, mint-on-claim (
_depositShareOriginreturnsaddress(0)): decrements_totalPendingDepositAssetsand mints new shares toreceiver. No asset transfer occurs since assets were already transferred duringrequestDeposit. -
Async, pre-minted (
_depositShareOriginreturns non-zero): transfers pre-minted shares from the share origin address toreceiver.
Emits IERC4626.Deposit. Per ERC-7540, the first event parameter is the controller in async
mode and msg.sender in sync mode.
_requestRedeem(uint256 shares, address controller, address owner, uint256 requestId) internal
Internal handler for redeem Requests. Assumes control of shares from owner and
emits IERC7540Redeem.RedeemRequest. requestRedeem uses the requestId returned by
_getRedeemRequestId.
Strategies that track Requests separately (e.g. ERC7540DelayRedeem, ERC7540EpochRedeem) record the
Request under requestId. Other callers of this function are expected to pass the value returned by
_getRedeemRequestId, so that the Request is recorded under the current maturity timepoint or epoch.
|
Share custody depends on _redeemShareDestination:
-
address(0)(default): shares are burned immediately and_totalPendingRedeemSharesis incremented to keep_totalOutstandingSharesaccurate. -
Non-zero address: shares are transferred to that address and held until fulfillment.
Authorization for a msg.sender not equal to owner is checked via operator status first;
if that fails, ERC-20 allowance is spent via ERC20._spendAllowance. This dual-authorization
approach is consistent with ERC-6909 semantics.
Requirements:
-
_isRedeemAsyncmust returntrue, otherwise reverts withERC7540SyncRedeem.
_burnSharesOnRedeemFulfill(uint256, uint256 shares) internal
Burns shares from _redeemShareDestination as part of redeem fulfillment when using
the escrow share custody model. Increments totalPendingRedeemShares by shares.
This function requires _redeemShareDestination to return a non-zero address.
When _redeemShareDestination returns address(0), shares were already burned at request
time inside _requestRedeem and this function must not be called.
|
_withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares) internal
Common workflow for withdraw and redeem claim operations.
Handles two cases depending on the vault configuration:
-
Synchronous (
_isRedeemAsyncreturnsfalse): spends ERC-20 allowance ifcalleris notowner, burns shares fromowner, and transfers underlying assets toreceiver. -
Async: decrements
_totalPendingRedeemShares(shares were already burned/escrowed during the Request or fulfillment phase) and transfers underlying assets toreceiver.
Emits IERC4626.Withdraw.
_transferIn(address from, uint256 assets) internal
Performs a transfer-in of underlying assets from from to the vault.
The default implementation uses SafeERC20.safeTransferFrom. Used by _deposit (sync) and
_requestDeposit (async).
_transferOut(address to, uint256 assets) internal
Performs a transfer-out of underlying assets from the vault to to.
The default implementation uses SafeERC20.safeTransfer. Used by _withdraw.
_decimalsOffset() → uint8 internal
Returns the decimal offset used for virtual shares/assets in _convertToShares and
_convertToAssets. Defaults to 0. Increase to strengthen inflation-attack protection
at the cost of share-price granularity.
_depositShareOrigin() → address internal
Returns the address from which shares are transferred to the receiver on deposit claim.
-
address(0)(default): shares are minted directly to the receiver at claim time. Pending deposit assets are tracked viatotalPendingDepositAssetsand decremented in_deposit. -
Non-zero address: shares are pre-minted to this address during fulfillment (via
_mintSharesOnDepositFulfill) and transferred to the receiver on claim.
If overridden to return a non-zero address, that address must not be able to transfer
shares (otherwise pre-minted shares could be moved before they are claimed). Use an unowned
address such as address(0xdead). Avoid addresses in the precompile reserved range
(address(1) through address(0x1ff), see EIP-7587).
|
The returned address (and whether it is zero) MUST be immutable for the vault’s
lifetime. Request, fulfillment, and claim stages, as well as the totalAssets and _totalOutstandingShares
views, read this hook independently, so a value that changes between stages settles different
stages under different custody rules and corrupts pending-asset / share accounting.
|
_redeemShareDestination() → address internal
Returns the address to which shares are transferred (escrowed) on redeem request.
-
address(0)(default): shares are burned immediately at request time. Pending redeem shares are tracked viatotalPendingRedeemSharesso that_totalOutstandingSharesremains accurate. -
Non-zero address: shares are transferred to this address on request and burned during fulfillment (via
_burnSharesOnRedeemFulfill).
If overridden to return a non-zero address, that address must not be able to transfer
shares (otherwise escrowed shares could be moved before they are burned). Use an unowned
address such as address(0xdead). Avoid addresses in the precompile reserved range
(address(1) through address(0x1ff), see EIP-7587).
|
| The returned address (and whether it is zero) MUST be immutable for the vault’s lifetime. Request, fulfillment, and claim stages read this hook independently, so a value that changes between stages settles different stages under different custody rules and corrupts pending-share / asset accounting. |
_isDepositAsync() → bool internal
Returns true if the deposit flow is asynchronous (Request-based). When false, deposit and
mint behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async deposit fulfillment strategy.
_isRedeemAsync() → bool internal
Returns true if the redeem flow is asynchronous (Request-based). When false, withdraw and
redeem behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async redeem fulfillment strategy.
_getDepositRequestId(address) → uint256 internal
Returns the requestId of a deposit Request submitted now for controller. Strategies that aggregate
all the deposit Requests of a controller return 0; others track Requests separately (e.g. by epoch or by
maturity timepoint). Not view, so that strategies can update their state when assigning an id (e.g. a
counter incremented on each Request).
_getRedeemRequestId(address) → uint256 internal
Returns the requestId of a redeem Request submitted now for controller. Strategies that aggregate
all the redeem Requests of a controller return 0; others track Requests separately (e.g. by epoch or by
maturity timepoint). Not view, so that strategies can update their state when assigning an id (e.g. a
counter incremented on each Request).
_pendingDepositRequest(uint256, address) → uint256 internal
Returns the amount of assets in Pending state for controller with the given requestId.
_claimableDepositRequest(uint256, address) → uint256 internal
Returns the amount of assets in Claimable state for controller with the given requestId.
_pendingRedeemRequest(uint256, address) → uint256 internal
Returns the amount of shares in Pending state for controller with the given requestId.
_claimableRedeemRequest(uint256, address) → uint256 internal
Returns the amount of shares in Claimable state for controller with the given requestId.
_consumeClaimableDeposit(uint256, address) → uint256 internal
Consumes assets worth of a Claimable deposit for controller and returns the corresponding
number of shares. Called by deposit (three-argument overload) in async mode.
In async mode, this function may be susceptible to the inflation attack vector described in
ERC-4626 security considerations
if the shares are freed automatically (e.g. after a certain time period). Consider using _decimalsOffset
to mitigate this risk.
|
_consumeClaimableMint(uint256, address) → uint256 internal
Consumes shares worth of a Claimable deposit for controller and returns the corresponding
number of assets. Called by mint (three-argument overload) in async mode.
_consumeClaimableWithdraw(uint256, address) → uint256 internal
Consumes assets worth of a Claimable redeem for controller and returns the corresponding
number of shares. Called by withdraw in async mode.
_consumeClaimableRedeem(uint256, address) → uint256 internal
Consumes shares worth of a Claimable redeem for controller and returns the corresponding
number of assets. Called by redeem in async mode.
_asyncMaxDeposit(address) → uint256 internal
Returns the maximum assets that can be claimed via deposit for an async owner.
_asyncMaxMint(address) → uint256 internal
Returns the maximum shares that can be claimed via mint for an async owner.
_asyncMaxWithdraw(address) → uint256 internal
Returns the maximum assets that can be claimed via withdraw for an async owner.
_asyncMaxRedeem(address) → uint256 internal
Returns the maximum shares that can be claimed via redeem for an async owner.
_totalClaimableDepositAssets() → uint256 internal
Returns the assets of Claimable deposit Requests that are still counted in
totalPendingDepositAssets, i.e. assets fulfilled at a locked rate whose shares are minted at
claim time. They are added back to totalAssets so that the vault’s exchange rate treats these
Requests as settled.
Returning 0 is correct for synchronous deposits, for strategies that do not lock a rate at fulfillment
(e.g. the rate is computed at claim time), and for the pre-mint custody model (see _depositShareOrigin),
where fulfillment already removes the assets from totalPendingDepositAssets. Strategies that lock
a rate at fulfillment with mint-on-claim custody must report them, together with
_totalClaimableDepositShares.
_totalClaimableDepositShares() → uint256 internal
Returns the shares owed to Claimable deposit Requests that have not been minted yet. They are
added to _totalOutstandingShares so that the vault’s exchange rate treats these Requests as settled.
_totalClaimableRedeemAssets() → uint256 internal
Returns the assets owed to Claimable redeem Requests, still held by the vault until claimed.
They are subtracted from totalAssets so that the vault’s exchange rate treats these Requests as
settled.
Returning 0 is correct for synchronous redemptions and for strategies that do not lock a rate at
fulfillment (e.g. the rate is computed at claim time). Strategies that lock a rate at fulfillment
must report them, together with _totalClaimableRedeemShares.
_totalClaimableRedeemShares() → uint256 internal
Returns the shares of Claimable redeem Requests, still counted in totalPendingRedeemShares
until claimed. They are subtracted from _totalOutstandingShares so that the vault’s exchange
rate treats these Requests as settled.
ERC7540InvalidOperator(address controller, address operator) error
The operator is not the caller or an approved operator of the controller.
ERC7540InvalidSelfOperator(address controller) error
The controller cannot set (or unset) itself as its own operator.
ERC7540SyncDeposit() error
A deposit Request was attempted but _isDepositAsync returns false.
ERC7540AsyncDeposit() error
A synchronous deposit preview was attempted but _isDepositAsync returns true.
ERC7540SyncRedeem() error
A redeem Request was attempted but _isRedeemAsync returns false.
ERC7540AsyncRedeem() error
A synchronous redeem preview was attempted but _isRedeemAsync returns true.
ERC7540MissingAsync() error
Neither _isDepositAsync nor _isRedeemAsync returns true.
ERC7540UnauthorizedMintSharesOnDepositFulfill() error
Invalid attempt at minting shares on a deposit fulfill when configuration mints them during claim.
ERC7540AdminDeposit
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540AdminDeposit.sol";
Admin-controlled (operator-triggered) fulfillment strategy for asynchronous deposits.
Extends ERC7540 with a deposit flow where a privileged caller explicitly transitions requests
from Pending to Claimable by calling _fulfillDeposit. The caller provides both the assets
amount and the corresponding shares, giving the fulfiller explicit control over the exchange rate.
This is the most flexible fulfillment model. Epoch-based batch settlement, FIFO queues, and cross-chain oracle-gated settlement can all be composed on top.
Production equivalents include USDai, Nest (Plume), MetaVault, and Centrifuge.
All requests share requestId = 0 (per-controller accounting only).
Claims through deposit and mint are priced with the ratio between maxDeposit and maxMint, which default to the
controller’s claimable assets and shares, and claiming either limit in full consumes the whole claimable
deposit. Overrides of maxDeposit or maxMint must keep both limits at the same ratio, otherwise a claim can be priced
at a different rate than the one locked at fulfillment.
|
_isDepositAsync() → bool internal
Returns true if the deposit flow is asynchronous (Request-based). When false, deposit and
mint behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async deposit fulfillment strategy.
_getDepositRequestId(address) → uint256 internal
All the Requests of a controller are aggregated under requestId = 0.
_requestDeposit(uint256 assets, address controller, address owner, uint256 requestId) internal
Records per-controller pending state after delegating to ERC7540._requestDeposit.
_fulfillDeposit(uint256 assets, uint256 shares, address controller) internal
Fulfills a pending deposit request by transitioning it from Pending to Claimable state.
The caller provides both assets and shares, locking the exchange rate at fulfillment time.
The fulfiller should ensure the vault’s totalAssets() already reflects the deposited assets
(e.g. after deploying them to a yield source) to avoid diluting existing holders.
Emits a DepositClaimable event.
Requirements:
-
assetsmust not exceed the pending deposit amount for thecontroller.
Multiple fulfillments with different exchange rates will blend into a weighted average.
For example, fulfilling 50 assets → 100 shares (2:1) then 50 assets → 25 shares (0.5:1) produces
claimableAssets=100 and claimableShares=125. A partial claim of 50 assets yields
mulDiv(50, 125, 100) = 62 shares: the weighted average rate, not either original rate.
Integrators expecting per-fulfillment rate isolation should use a different strategy (e.g. epochs).
|
_consumeClaimableDeposit(uint256 assets, address controller) → uint256 internal
Consumes assets from the claimable deposit and returns the proportional shares (rounded down).
_consumeClaimableMint(uint256 shares, address controller) → uint256 internal
Consumes shares from the claimable deposit and returns the proportional assets (rounded up).
_pendingDepositRequest(uint256, address controller) → uint256 internal
Returns the amount of assets in Pending state for controller with the given requestId.
_claimableDepositRequest(uint256, address controller) → uint256 internal
Returns the amount of assets in Claimable state for controller with the given requestId.
_asyncMaxDeposit(address owner) → uint256 internal
Returns the maximum assets that can be claimed via deposit for an async owner.
_asyncMaxMint(address owner) → uint256 internal
Returns the maximum shares that can be claimed via mint for an async owner.
_totalClaimableDepositAssets() → uint256 internal
Assets of fulfilled but unclaimed deposits. Only tracked in mint-on-claim custody: with pre-mint
custody, fulfillment already settles them in totalPendingDepositAssets and _totalOutstandingShares.
_totalClaimableDepositShares() → uint256 internal
Shares owed to fulfilled but unclaimed deposits. See _totalClaimableDepositAssets.
ERC7540AdminRedeem
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540AdminRedeem.sol";
Admin-controlled (operator-triggered) fulfillment strategy for asynchronous redemptions.
Extends ERC7540 with a redeem flow where a privileged caller explicitly transitions requests
from Pending to Claimable by calling _fulfillRedeem. The caller provides both the shares
amount and the corresponding assets, giving the fulfiller explicit control over the exchange rate.
The fulfiller must ensure the vault holds enough underlying assets before calling _fulfillRedeem.
Asset sourcing (unwinding positions, bridging cross-chain, etc.) is application-specific and is
not part of this contract.
Production equivalents include USDai, Nest (Plume), MetaVault, and Centrifuge.
All requests share requestId = 0 (per-controller accounting only).
Claims through withdraw and redeem are priced with the ratio between maxWithdraw and maxRedeem, which default to the
controller’s claimable assets and shares, and claiming either limit in full consumes the whole claimable
redeem. Overrides of maxWithdraw or maxRedeem must keep both limits at the same ratio, otherwise a claim can be priced
at a different rate than the one locked at fulfillment.
|
_isRedeemAsync() → bool internal
Returns true if the redeem flow is asynchronous (Request-based). When false, withdraw and
redeem behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async redeem fulfillment strategy.
_getRedeemRequestId(address) → uint256 internal
All the Requests of a controller are aggregated under requestId = 0.
_requestRedeem(uint256 shares, address controller, address owner, uint256 requestId) internal
Records per-controller pending state before delegating to ERC7540._requestRedeem.
_fulfillRedeem(uint256 shares, uint256 assets, address controller) internal
Fulfills a pending redeem request by transitioning it from Pending to Claimable state.
The caller provides both shares and assets, locking the exchange rate at fulfillment time.
The fulfiller must ensure the vault holds enough underlying assets to cover the assets amount
before calling this function (see _isSolvent).
Emits a RedeemClaimable event.
Requirements:
-
sharesmust not exceed the pending redeem amount for thecontroller. -
The vault must hold enough assets to cover pending deposits and Claimable redeems, including this one.
_consumeClaimableWithdraw(uint256 assets, address controller) → uint256 internal
Consumes assets from the claimable redeem and returns the proportional shares (rounded up).
_consumeClaimableRedeem(uint256 shares, address controller) → uint256 internal
Consumes shares from the claimable redeem and returns the proportional assets (rounded down).
_pendingRedeemRequest(uint256, address controller) → uint256 internal
Returns the amount of shares in Pending state for controller with the given requestId.
_claimableRedeemRequest(uint256, address controller) → uint256 internal
Returns the amount of shares in Claimable state for controller with the given requestId.
_asyncMaxWithdraw(address owner) → uint256 internal
Returns the maximum assets that can be claimed via withdraw for an async owner.
_asyncMaxRedeem(address owner) → uint256 internal
Returns the maximum shares that can be claimed via redeem for an async owner.
ERC7540DelayDeposit
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540DelayDeposit.sol";
Time-delay fulfillment strategy for asynchronous deposits.
Extends ERC7540 with a deposit flow where requests become claimable automatically after a
configurable waiting period. No privileged fulfiller is needed: once the delay elapses, the
controller or one of its operators can claim. The exchange rate is computed at claim time using the vault’s
live convertToShares.
Production equivalents (redeem side): BeefySonic, MagmaV2, Tangle.
Requests are tracked using Checkpoints.Trace208, storing cumulative deposit amounts keyed by
their maturity timepoint. The requestId returned by requestDeposit equals the absolute
timestamp at which the request becomes claimable (clock() + depositDelay(controller)).
Override depositDelay to customize the waiting period (default: 1 hour) and clock to
change the time source (default: block.timestamp).
Since claims are priced at the live rate, a donation to the vault before a request is claimed
lowers the shares it receives, down to zero for small requests. Pending requests are visible for the whole
delay and cannot be cancelled, which makes this donation (inflation) attack easier to set up than against a
plain ERC4626. Consider a non-zero _decimalsOffset to make it unprofitable. See the
ERC-4626 inflation attack guide.
|
This module does not support temporary share custody through _depositShareOrigin. The constructor
tries to enforce that property, but the check runs once at construction and only sees the value
_depositShareOrigin returns then, so it cannot catch an override that reads storage written later. Such an
override MUST also keep that value constant for the vault’s lifetime.
|
clock() → uint48 public
See IERC6372.clock. Defaults to block.timestamp.
Overriding this function to use a different time source also requires overriding CLOCK_MODE
(e.g. with ERC6372Utils.blockNumberClockMode for a block number clock). The default CLOCK_MODE
reverts when clock does not return block.timestamp.
|
CLOCK_MODE() → string public
Returns a machine-readable description of the clock, formatted as a URL query string.
Timestamps are described as mode=timestamp and block numbers as mode=blocknumber&from=default,
where default becomes a CAIP-2 chain ID (e.g. eip155:1) if the block number is not that of the
NUMBER opcode (0x43). Any other mode uses a unique identifier for the mode field.
depositDelay(address) → uint48 public
Returns the delay duration before a deposit request becomes claimable. Defaults to 1 hour.
For any given controller, the maturity timepoint clock() + depositDelay(controller) MUST
be non-decreasing across successive requestDeposit calls. Overrides that shrink the delay faster
than clock() advances will cause new requests to revert until the previous maturity is reached.
|
_isDepositAsync() → bool internal
Returns true if the deposit flow is asynchronous (Request-based). When false, deposit and
mint behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async deposit fulfillment strategy.
_requestDeposit(uint256 assets, address controller, address owner, uint256 requestId) internal
Delegates to ERC7540._requestDeposit, then pushes a new cumulative checkpoint at the maturity
timepoint requestId (see _getDepositRequestId).
_getDepositRequestId(address controller) → uint256 internal
Deposit Requests are identified by their maturity timepoint: the current clock plus depositDelay.
_consumeClaimableDeposit(uint256 assets, address controller) → uint256 internal
Consumes assets from claimable deposits, returns their value in shares at the current rate (rounded down).
_consumeClaimableMint(uint256 shares, address controller) → uint256 internal
Consumes the assets worth shares at the current rate (rounded up) from claimable deposits and returns them.
Minting the full maxMint consumes all of the claimable assets.
_pendingDepositRequest(uint256 requestId, address controller) → uint256 internal
Returns the assets in Pending state for a specific requestId (timepoint).
A request is pending only if its timepoint is strictly in the future.
_claimableDepositRequest(uint256 requestId, address controller) → uint256 internal
Returns the assets in Claimable state for a specific requestId (timepoint).
A request is claimable once its timepoint has elapsed and the assets haven’t been claimed yet.
_asyncMaxDeposit(address owner) → uint256 internal
Returns the total claimable assets across all matured timepoints for owner.
_asyncMaxMint(address owner) → uint256 internal
Returns the share-equivalent of _asyncMaxDeposit (rounded down).
_readyDepositAt(address owner, uint48 timepoint) → uint256 internal
Internal helper: fetch the amount that is expected to be claimable at a given timepoint, if any. Any amount that has already been claimed is taken into consideration.
_totalClaimableDepositAssets() → uint256 internal
The rate is computed at claim time, so no value is locked in Claimable requests.
_totalClaimableDepositShares() → uint256 internal
The rate is computed at claim time, so no value is locked in Claimable requests.
ERC7540DelayInvalidDepositShareOrigin() error
Triggered if _depositShareOrigin is not address(0), as this is not supported by this module.
ERC7540DelayRedeem
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540DelayRedeem.sol";
Time-delay fulfillment strategy for asynchronous redemptions.
Extends ERC7540 with a redeem flow where requests become claimable automatically after a
configurable waiting period. No privileged fulfiller is needed: once the delay elapses, the
controller or one of its operators can claim. The exchange rate is computed at claim time using the vault’s
live convertToAssets.
Production equivalents: BeefySonic (protocol-dictated SFC unbonding), MagmaV2 (admin-configurable delay), Tangle (protocol-dictated).
Requests are tracked using Checkpoints.Trace208, storing cumulative redeem amounts keyed by
their maturity timepoint. The requestId returned by requestRedeem equals the absolute
timestamp at which the request becomes claimable (clock() + redeemDelay(controller)).
Override redeemDelay to customize the waiting period (default: 1 hour) and clock to
change the time source (default: block.timestamp).
This module does not support temporary share custody through _redeemShareDestination. The constructor
tries to enforce that property, but the check runs once at construction and only sees the value
_redeemShareDestination returns then, so it cannot catch an override that reads storage written later.
Such an override MUST also keep that value constant for the vault’s lifetime.
|
clock() → uint48 public
See IERC6372.clock. Defaults to block.timestamp.
Overriding this function to use a different time source also requires overriding CLOCK_MODE
(e.g. with ERC6372Utils.blockNumberClockMode for a block number clock). The default CLOCK_MODE
reverts when clock does not return block.timestamp.
|
CLOCK_MODE() → string public
Returns a machine-readable description of the clock, formatted as a URL query string.
Timestamps are described as mode=timestamp and block numbers as mode=blocknumber&from=default,
where default becomes a CAIP-2 chain ID (e.g. eip155:1) if the block number is not that of the
NUMBER opcode (0x43). Any other mode uses a unique identifier for the mode field.
redeemDelay(address) → uint48 public
Returns the delay duration before a redeem request becomes claimable. Defaults to 1 hour.
For any given controller, the maturity timepoint clock() + redeemDelay(controller) MUST
be non-decreasing across successive requestRedeem calls. Overrides that shrink the delay faster
than clock() advances will cause new requests to revert until the previous maturity is reached.
|
_isRedeemAsync() → bool internal
Returns true if the redeem flow is asynchronous (Request-based). When false, withdraw and
redeem behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async redeem fulfillment strategy.
_requestRedeem(uint256 shares, address controller, address owner, uint256 requestId) internal
Pushes a new cumulative checkpoint at the maturity timepoint requestId (see
_getRedeemRequestId) and delegates to ERC7540._requestRedeem.
_getRedeemRequestId(address controller) → uint256 internal
Redeem Requests are identified by their maturity timepoint: the current clock plus redeemDelay.
_consumeClaimableWithdraw(uint256 assets, address controller) → uint256 internal
Consumes the shares worth assets at the current rate (rounded up) from claimable redeems and returns them.
Withdrawing the full maxWithdraw consumes all of the claimable shares.
_consumeClaimableRedeem(uint256 shares, address controller) → uint256 internal
Consumes shares from claimable redeems, returns their value in assets at the current rate (rounded down).
_pendingRedeemRequest(uint256 requestId, address controller) → uint256 internal
Returns the shares in Pending state for a specific requestId (timepoint).
A request is pending only if its timepoint is strictly in the future.
_claimableRedeemRequest(uint256 requestId, address controller) → uint256 internal
Returns the shares in Claimable state for a specific requestId (timepoint).
A request is claimable once its timepoint has elapsed and the shares haven’t been claimed yet.
_asyncMaxWithdraw(address owner) → uint256 internal
Returns the asset-equivalent of _asyncMaxRedeem (rounded down).
_asyncMaxRedeem(address owner) → uint256 internal
Returns the total claimable shares across all matured timepoints for owner.
_readyRedeemAt(address owner, uint48 timepoint) → uint256 internal
Internal helper: fetch the amount that is expected to be claimable at a given timepoint, if any. Any amount that has already been claimed is taken into consideration.
_totalClaimableRedeemAssets() → uint256 internal
The rate is computed at claim time, so no value is locked in Claimable requests.
_totalClaimableRedeemShares() → uint256 internal
The rate is computed at claim time, so no value is locked in Claimable requests.
ERC7540DelayInvalidRedeemShareDestination() error
Triggered if _redeemShareDestination is not address(0), as this is not supported by this module.
ERC7540EpochDeposit
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540EpochDeposit.sol";
Epoch-based batch fulfillment strategy for asynchronous deposits.
Extends ERC7540 with a deposit flow where requests submitted during the same epoch are batched
together and settled at a single exchange rate when the admin closes the epoch via _fulfillDeposit.
All controllers within a fulfilled epoch receive the same pro-rata conversion from assets to shares.
The requestId returned by requestDeposit is the epoch ID. By default, epochs are weekly
and start on Mondays ((block.timestamp + 3 days) / 1 weeks); override currentDepositEpoch to change
the cadence or use manually-bumped epoch counters.
Each account tracks its epoch memberships via a DoubleEndedQueue capped at
_depositRequestQueueLimit entries (default: 32) to bound the O(n) loops in _asyncMaxDeposit
and _asyncMaxMint. Claims free the slots of fully claimed epochs, but only from the front of the
queue: they stop at the oldest Pending epoch, so a controller at the limit cannot submit new requests
until that epoch is fulfilled (see _fulfillDeposit).
Each claim converts at the epoch’s remaining totalShares / totalAssets ratio and rounds
down, against the claimant. The rounding loss (less than 1 share unit per claim) stays in the
epoch and goes to the controllers who claim later; the last claimant receives the exact remainder.
With very small amounts the loss can be the whole claim: if an epoch settles 3 assets for 2 shares
across 3 controllers who requested 1 asset each, the first to claim receives 0 shares and the other
two receive 1 share each. With realistic token decimals the loss is negligible. Unlike the ERC-4626
inflation attack, these totals cannot be manipulated by donation: they only grow through
requestDeposit and _fulfillDeposit. To reduce the loss further, override _decimalsOffset so
that shares have more decimals than assets.
|
_isDepositAsync() → bool internal
Returns true if the deposit flow is asynchronous (Request-based). When false, deposit and
mint behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async deposit fulfillment strategy.
currentDepositEpoch() → uint256 public
Returns the current epoch ID. Defaults to (block.timestamp + 3 days) / 1 weeks, so
epochs transition at Monday 00:00 UTC (weeks start Monday).
Successive calls MUST never return a value smaller than any earlier one (they may
stay the same or grow). If a later call returns an epoch older than a controller’s queue tail,
the request enqueues a duplicate entry pointing at the same epoch’s shared accounting, which
double-counts in _asyncMaxDeposit / _asyncMaxMint and can settle caller-specified output
that was not backed by consumed state.
|
totalDepositAssets(uint256 epochId) → uint256 public
Returns the total assets queued in epochId. Equals the sum of all deposit requests
during the Pending phase; decreases as claimants consume their pro-rata share once the
epoch is fulfilled, and reaches 0 once the epoch is fully claimed.
totalDepositShares(uint256 epochId) → uint256 public
Returns the shares allocated to epochId at fulfillment. Zero before
_fulfillDeposit is called; decreases as claimants consume their pro-rata share.
Together with totalDepositAssets it encodes the locked epoch rate.
depositEpochs(address controller, uint256 start, uint256 end) → uint256[] epochIds public
Returns the deposit epoch IDs that controller has open requests in, in queue order
(oldest first). Fully claimed epochs are popped from the queue and no longer appear.
Using start = 0 and end = type(uint64).max will return the entire set of epochs.
_pendingDepositRequest(uint256 requestId, address controller) → uint256 internal
A request is pending if its epoch has not yet been fulfilled (totalShares == 0).
_claimableDepositRequest(uint256 requestId, address controller) → uint256 internal
A request is claimable if its epoch has been fulfilled (totalShares > 0).
_asyncMaxDeposit(address owner) → uint256 internal
Sums claimable assets from `owner’s fulfilled epochs oldest-first, stopping at the
first Pending epoch. Fulfilled epochs behind a Pending one are not counted until the
Pending one is fulfilled. Matches _consumeClaimableDeposit.
O(n) in owner’s epochs, bounded by for the entire epoch in a single write).
|
_asyncMaxMint(address owner) → uint256 internal
Sums claimable shares across all fulfilled epochs the owner participates in. Same as _asyncMaxDeposit.
_convertToDepositShares(uint256 epochId, uint256 assets, enum Math.Rounding rounding) → uint256 internal
Converts assets to shares at epochId’s locked rate. Returns 0 if `totalAssets is 0.
_convertToDepositAssets(uint256 epochId, uint256 shares, enum Math.Rounding rounding) → uint256 internal
Converts shares to assets at epochId’s locked rate. Returns 0 if `totalShares is 0.
_requestDeposit(uint256 assets, address controller, address owner, uint256 requestId) internal
Records the request in the current epoch and enqueues the epoch ID for controller
if not already present. A zero-amount request is a no-op at the epoch layer (it emits the
event via super but does not create an unfulfillable epoch or occupy a queue slot).
Requirements:
-
_msgSender()must becontrolleror an approved operator ofcontroller. This is a strict subset of ERC-7540 request auth (added on top of the base’sownercheck) to prevent third-party queue spam. -
The controller’s epoch queue must not exceed
_depositRequestQueueLimit.
_getDepositRequestId(address) → uint256 internal
Deposit Requests are identified by the epoch they are submitted in (see currentDepositEpoch).
_fulfillDeposit(uint256 epochId, uint256 totalShares) internal
Fulfills a past epoch by setting its totalShares. All requests within the epoch
become claimable at the rate totalShares / totalAssets.
| When epoch transition is manual, the caller should bump the epoch before calling this. |
Pending vs. fulfilled is distinguished by totalShares == 0. Admins are assumed not to
fulfill at zero (a confiscation event with no economic purpose); if 0 is passed by accident, the
call is a no-op (no event is emitted) and the admin can re-fulfill. This recovery only holds as
long as derived contracts preserve the no-side-effect semantics of this function — if not,
derived contracts should restrict totalShares != 0. A genuine total-loss settlement is not
representable in this encoding; deployers needing that SHOULD override to encode the fulfilled
state separately (e.g. an explicit boolean).
|
Out-of-order fulfillment is permitted, but each controller’s claims and queue
cleanup stay gated on their oldest Pending epoch (see _consumeClaimableDeposit). Funds
are not lost, but a controller at _depositRequestQueueLimit cannot submit new requests
until admin resolves the front, so admins should stay close to FIFO order. Until then,
claimableDepositRequest reports the newer epoch as Claimable while maxDeposit and maxMint do not
include it yet. Derived contracts wanting strict FIFO settlement should enforce it here.
|
Requirements:
-
epochIdmust be a past epoch (less thancurrentDepositEpoch). -
The epoch must have pending assets and must not have been fulfilled already.
_consumeClaimableDeposit(uint256 assets, address controller) → uint256 internal
Consumes assets from controller’s epochs oldest-first at each epoch’s locked rate,
dequeueing fully consumed ones. Breaks early when the oldest epoch is still Pending:
consuming from it would burn `assets for zero shares. Claims are therefore gated on the
oldest Pending epoch, matching _asyncMaxDeposit.
| Wrappers wanting stricter FIFO semantics should consider overriding to revert when the oldest epoch is Pending. |
When the epoch’s locked rate skews the assets : shares ratio (either direction),
a small assets input can round batchShares to zero; the epoch’s asset pool moves
without minting shares to the caller. At realistic ERC-20 decimals the per-call drift is
sub-cent. Deployers with non-standard decimals or a zero-drift requirement SHOULD override
to revert when batchAssets > 0 && batchShares == 0.
|
_consumeClaimableMint(uint256 shares, address controller) → uint256 internal
Same as _consumeClaimableDeposit but iterates by shares instead of assets.
When the claim exhausts the controller’s share entitlement in an epoch, the epoch is dequeued
and the controller’s entire asset request is consumed, so no residue is left behind. Partial
claims round the consumed assets up, against the caller: the rounding benefits the remaining
claimants of the epoch. If rounding up consumes the last assets of an epoch while shares remain,
these shares can no longer be claimed and are released to the vault (burned from
_depositShareOrigin when shares are minted at fulfillment).
_totalClaimableDepositAssets() → uint256 internal
Assets of fulfilled but unclaimed epochs. Only tracked in mint-on-claim custody: with pre-mint
custody, fulfillment already settles them in totalPendingDepositAssets and _totalOutstandingShares.
_totalClaimableDepositShares() → uint256 internal
Shares owed to fulfilled but unclaimed epochs. See _totalClaimableDepositAssets.
_depositRequestQueueLimit() → uint256 internal
Maximum number of epoch entries in a controller’s queue. Defaults to 32.
Prevents unbounded iteration in _asyncMaxDeposit and _asyncMaxMint.
ERC7540EpochDepositFulfilled(uint256 indexed epochId, uint256 totalAssets, uint256 totalShares) event
Emitted when a deposit epoch transitions from Pending to Claimable via _fulfillDeposit.
ERC7540EpochDepositTooEarly(uint256 epochId) error
Attempted to fulfill a deposit epoch that has not yet ended.
ERC7540EpochDepositEmptyEpoch(uint256 epochId) error
Attempted to fulfill a deposit epoch with no pending requests.
ERC7540EpochDepositAlreadyFulfilled(uint256 epochId) error
Attempted to fulfill a deposit epoch that has already been fulfilled.
ERC7540EpochDepositQueueLimitExceeded(address controller) error
Attempted to enqueue an epoch for controller past _depositRequestQueueLimit.
ERC7540EpochRedeem
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540EpochRedeem.sol";
Epoch-based batch fulfillment strategy for asynchronous redemptions.
Extends ERC7540 with a redeem flow where requests submitted during the same epoch are batched
together and settled at a single exchange rate when the admin closes the epoch via _fulfillRedeem.
All controllers within a fulfilled epoch receive the same pro-rata conversion from shares to assets.
The requestId returned by requestRedeem is the epoch ID. By default, epochs are weekly
and start on Mondays ((block.timestamp + 3 days) / 1 weeks); override currentRedeemEpoch to change
the cadence or use manually-bumped epoch counters.
Each account tracks its epoch memberships via a DoubleEndedQueue capped at
_redeemRequestQueueLimit entries (default: 32) to bound the O(n) loops in _asyncMaxWithdraw
and _asyncMaxRedeem. Claims free the slots of fully claimed epochs, but only from the front of the
queue: they stop at the oldest Pending epoch, so a controller at the limit cannot submit new requests
until that epoch is fulfilled (see _fulfillRedeem).
Each claim converts at the epoch’s remaining totalAssets / totalShares ratio and rounds
down, against the claimant. The rounding loss (less than 1 asset unit per claim) stays in the
epoch and goes to the controllers who claim later; the last claimant receives the exact remainder.
With very small amounts the loss can be the whole claim: if an epoch settles 3 shares for 2 assets
across 3 controllers who requested 1 share each, the first to claim receives 0 assets and the other
two receive 1 asset each. With realistic token decimals the loss is negligible. Unlike the ERC-4626
inflation attack, these totals cannot be manipulated by donation: they only grow through
requestRedeem and _fulfillRedeem.
|
_isRedeemAsync() → bool internal
Returns true if the redeem flow is asynchronous (Request-based). When false, withdraw and
redeem behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async redeem fulfillment strategy.
currentRedeemEpoch() → uint256 public
Returns the current epoch ID. Defaults to (block.timestamp + 3 days) / 1 weeks, so
epochs transition at Monday 00:00 UTC (weeks start Monday).
Successive calls MUST never return a value smaller than any earlier one (they may
stay the same or grow). If a later call returns an epoch older than a controller’s queue tail,
the request enqueues a duplicate entry pointing at the same epoch’s shared accounting, which
double-counts in _asyncMaxWithdraw / _asyncMaxRedeem and can settle caller-specified output
that was not backed by consumed state.
|
totalRedeemShares(uint256 epochId) → uint256 public
Returns the total shares queued in epochId. Equals the sum of all redeem requests
during the Pending phase; decreases as claimants consume their pro-rata share once the
epoch is fulfilled, and reaches 0 once the epoch is fully claimed.
totalRedeemAssets(uint256 epochId) → uint256 public
Returns the assets allocated to epochId at fulfillment. Zero before
_fulfillRedeem is called; decreases as claimants consume their pro-rata share.
Together with totalRedeemShares it encodes the locked epoch rate.
redeemEpochs(address controller, uint256 start, uint256 end) → uint256[] epochIds public
Returns the redeem epoch IDs that controller has open requests in, in queue order
(oldest first). Fully claimed epochs are popped from the queue and no longer appear.
Using start = 0 and end = type(uint64).max will return the entire set of epochs.
_pendingRedeemRequest(uint256 requestId, address controller) → uint256 internal
A request is pending if its epoch has not yet been fulfilled (totalAssets == 0).
_claimableRedeemRequest(uint256 requestId, address controller) → uint256 internal
A request is claimable if its epoch has been fulfilled (totalAssets > 0).
_asyncMaxWithdraw(address owner) → uint256 internal
Sums claimable assets from `owner’s fulfilled epochs oldest-first, stopping at the
first Pending epoch. Fulfilled epochs behind a Pending one are not counted until the
Pending one is fulfilled. Matches _consumeClaimableWithdraw.
O(n) in owner’s epochs, bounded by for the entire epoch in a single write).
|
_asyncMaxRedeem(address owner) → uint256 internal
Sums claimable shares across all fulfilled epochs the owner participates in. Same as _asyncMaxWithdraw.
_convertToRedeemAssets(uint256 epochId, uint256 shares, enum Math.Rounding rounding) → uint256 internal
Converts shares to assets at epochId’s locked rate. Returns 0 if `totalShares is 0.
_convertToRedeemShares(uint256 epochId, uint256 assets, enum Math.Rounding rounding) → uint256 internal
Converts assets to shares at epochId’s locked rate. Returns 0 if `totalAssets is 0.
_requestRedeem(uint256 shares, address controller, address owner, uint256 requestId) internal
Records the request in the current epoch and enqueues the epoch ID for controller
if not already present. A zero-amount request is a no-op at the epoch layer (it emits the
event via super but does not create an unfulfillable epoch or occupy a queue slot).
Requirements:
-
_msgSender()must becontrolleror an approved operator ofcontroller. This is a strict subset of ERC-7540 request auth (added on top of the base’sownerallowance/operator check) to prevent third-party queue spam. -
The controller’s epoch queue must not exceed
_redeemRequestQueueLimit.
_getRedeemRequestId(address) → uint256 internal
Redeem Requests are identified by the epoch they are submitted in (see currentRedeemEpoch).
_fulfillRedeem(uint256 epochId, uint256 totalAssets) internal
Fulfills a past epoch by setting its totalAssets. All requests within the epoch
become claimable at the rate totalAssets / totalShares.
| When epoch transition is manual, the caller should bump the epoch before calling this. |
Pending vs. fulfilled is distinguished by totalAssets == 0. Admins are assumed not to
fulfill at zero (a confiscation event with no economic purpose); if 0 is passed by accident, the
call is a no-op (no event is emitted) and the admin can re-fulfill. This recovery only holds as
long as derived contracts preserve the no-side-effect semantics of this function — if not,
derived contracts should restrict totalAssets != 0. A genuine total-loss settlement is not
representable in this encoding; deployers needing that SHOULD override to encode the fulfilled
state separately (e.g. an explicit boolean).
|
Out-of-order fulfillment is permitted, but each controller’s claims and queue
cleanup stay gated on their oldest Pending epoch (see _consumeClaimableWithdraw). Funds
are not lost, but a controller at _redeemRequestQueueLimit cannot submit new requests
until admin resolves the front, so admins should stay close to FIFO order. Until then,
claimableRedeemRequest reports the newer epoch as Claimable while maxWithdraw and maxRedeem do not
include it yet. Derived contracts wanting strict FIFO settlement should enforce it here.
|
Requirements:
-
epochIdmust be a past epoch (less thancurrentRedeemEpoch). -
The epoch must have pending shares and must not have been fulfilled already.
-
The vault must hold enough assets to cover pending deposits and Claimable redeems, including this epoch.
_consumeClaimableWithdraw(uint256 assets, address controller) → uint256 internal
Consumes assets from controller’s epochs oldest-first at each epoch’s locked rate,
dequeueing fully consumed ones. Breaks early when the oldest epoch is still Pending:
consuming from it would burn `assets for zero shares. Claims are therefore gated on the
oldest Pending epoch, matching _asyncMaxWithdraw.
| Wrappers wanting stricter FIFO semantics should consider overriding to revert when the oldest epoch is Pending. |
When the claim exhausts the controller’s asset entitlement in an epoch, the epoch is dequeued and the controller’s entire share request is consumed, so no residue is left behind. Partial claims round the consumed shares up, against the caller: the rounding benefits the remaining claimants of the epoch. If rounding up consumes the last shares of an epoch while assets remain, these assets can no longer be claimed and are released to the vault, where they accrue to the remaining shareholders.
_consumeClaimableRedeem(uint256 shares, address controller) → uint256 internal
Same as _consumeClaimableWithdraw but iterates by shares instead of assets.
When the epoch’s locked rate skews the shares : assets ratio (either direction),
a small shares input can round batchAssets to zero; the epoch’s share pool moves
without paying assets to the caller. At realistic ERC-20 decimals the per-call drift is
sub-cent. Deployers with non-standard decimals or a zero-drift requirement SHOULD override
to revert when batchShares > 0 && batchAssets == 0.
|
_redeemRequestQueueLimit() → uint256 internal
Maximum number of epoch entries in a controller’s queue. Defaults to 32.
Prevents unbounded iteration in _asyncMaxWithdraw and _asyncMaxRedeem.
ERC7540EpochRedeemFulfilled(uint256 indexed epochId, uint256 totalShares, uint256 totalAssets) event
Emitted when a redeem epoch transitions from Pending to Claimable via _fulfillRedeem.
ERC7540EpochRedeemTooEarly(uint256 epochId) error
Attempted to fulfill a redeem epoch that has not yet ended.
ERC7540EpochRedeemEmptyEpoch(uint256 epochId) error
Attempted to fulfill a redeem epoch with no pending requests.
ERC7540EpochRedeemAlreadyFulfilled(uint256 epochId) error
Attempted to fulfill a redeem epoch that has already been fulfilled.
ERC7540EpochRedeemQueueLimitExceeded(address controller) error
Attempted to enqueue an epoch for controller past _redeemRequestQueueLimit.
ERC7540SyncDeposit
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540SyncDeposit.sol";
Module for enabling synchronous behavior (ERC-4626) for the deposit flow of an ERC-7540 vault.
Note that an ERC-7540 vault is required to have at least one flow operating in asynchronous mode, so this module
cannot be combined with ERC7540SyncRedeem.
_isDepositAsync() → bool internal
Returns true if the deposit flow is asynchronous (Request-based). When false, deposit and
mint behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async deposit fulfillment strategy.
_consumeClaimableDeposit(uint256, address) → uint256 internal
Consumes assets from the claimable deposit and returns the proportional shares (rounded down).
_consumeClaimableMint(uint256, address) → uint256 internal
Consumes shares from the claimable deposit and returns the proportional assets (rounded up).
_pendingDepositRequest(uint256, address) → uint256 internal
Returns the amount of assets in Pending state for controller with the given requestId.
_claimableDepositRequest(uint256, address) → uint256 internal
Returns the amount of assets in Claimable state for controller with the given requestId.
_asyncMaxDeposit(address) → uint256 internal
Returns the maximum assets that can be claimed via deposit for an async owner.
_asyncMaxMint(address) → uint256 internal
Returns the maximum shares that can be claimed via mint for an async owner.
_getDepositRequestId(address) → uint256 internal
Synchronous flows have no Requests: _requestDeposit reverts before using this value.
ERC7540SyncRedeem
import "@openzeppelin/contracts/token/ERC20/extensions/ERC7540SyncRedeem.sol";
Module for enabling synchronous behavior (ERC-4626) for the redeem flow of an ERC-7540 vault.
Note that an ERC-7540 vault is required to have at least one flow operating in asynchronous mode, so this module
cannot be combined with ERC7540SyncDeposit.
_isRedeemAsync() → bool internal
Returns true if the redeem flow is asynchronous (Request-based). When false, withdraw and
redeem behave as standard synchronous ERC-4626 operations.
Override to return true in extensions that provide an async redeem fulfillment strategy.
_consumeClaimableWithdraw(uint256, address) → uint256 internal
Consumes assets from the claimable redeem and returns the proportional shares (rounded up).
_consumeClaimableRedeem(uint256, address) → uint256 internal
Consumes shares from the claimable redeem and returns the proportional assets (rounded down).
_pendingRedeemRequest(uint256, address) → uint256 internal
Returns the amount of shares in Pending state for controller with the given requestId.
_claimableRedeemRequest(uint256, address) → uint256 internal
Returns the amount of shares in Claimable state for controller with the given requestId.
_asyncMaxWithdraw(address) → uint256 internal
Returns the maximum assets that can be claimed via withdraw for an async owner.
_asyncMaxRedeem(address) → uint256 internal
Returns the maximum shares that can be claimed via redeem for an async owner.
_getRedeemRequestId(address) → uint256 internal
Synchronous flows have no Requests: _requestRedeem reverts before using this value.
Utilities
SafeERC20
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
Wrappers around ERC-20 operations that throw on failure (when the token
contract returns false). Tokens that return no value (and instead revert or
throw on failure) are also supported, non-reverting calls are assumed to be
successful.
To use this library you can add a using SafeERC20 for IERC20; statement to your contract,
which allows you to call the safe operations as token.safeTransfer(…), etc.
safeTransfer(contract IERC20 token, address to, uint256 value) internal
Transfer value amount of token from the calling contract to to. If token returns no value,
non-reverting calls are assumed to be successful.
safeTransferFrom(contract IERC20 token, address from, address to, uint256 value) internal
Transfer value amount of token from from to to, spending the approval given by from to the
calling contract. If token returns no value, non-reverting calls are assumed to be successful.
trySafeTransfer(contract IERC20 token, address to, uint256 value) → bool internal
Variant of safeTransfer that returns a bool instead of reverting if the operation is not successful.
trySafeTransferFrom(contract IERC20 token, address from, address to, uint256 value) → bool internal
Variant of safeTransferFrom that returns a bool instead of reverting if the operation is not successful.
safeIncreaseAllowance(contract IERC20 token, address spender, uint256 value) internal
Increase the calling contract’s allowance toward spender by value. If token returns no value,
non-reverting calls are assumed to be successful.
If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
this function. Performing a safeIncreaseAllowance or safeDecreaseAllowance operation on a token contract
that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
|
safeDecreaseAllowance(contract IERC20 token, address spender, uint256 requestedDecrease) internal
Decrease the calling contract’s allowance toward spender by requestedDecrease. If token returns no
value, non-reverting calls are assumed to be successful.
If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
this function. Performing a safeIncreaseAllowance or safeDecreaseAllowance operation on a token contract
that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
|
forceApprove(contract IERC20 token, address spender, uint256 value) internal
Set the calling contract’s allowance toward spender to value. If token returns no value,
non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
to be set to zero before setting it to a non-zero value, such as USDT.
| If the token implements ERC-7674, this function will not modify any temporary allowance. This function only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being set here. |
transferAndCallRelaxed(contract IERC1363 token, address to, uint256 value, bytes data) internal
Performs an ERC1363 transferAndCall, with a fallback to the simple ERC20 transfer if the target has no
code. This can be used to implement an ERC721-like safe transfer that relies on ERC1363 checks when
targeting contracts.
Reverts if the returned value is other than true.
transferFromAndCallRelaxed(contract IERC1363 token, address from, address to, uint256 value, bytes data) internal
Performs an ERC1363 transferFromAndCall, with a fallback to the simple ERC20 transferFrom if the target
has no code. This can be used to implement an ERC721-like safe transfer that relies on ERC1363 checks when
targeting contracts.
Reverts if the returned value is other than true.
approveAndCallRelaxed(contract IERC1363 token, address to, uint256 value, bytes data) internal
Performs an ERC1363 approveAndCall, with a fallback to the simple ERC20 approve if the target has no
code. This can be used to implement an ERC721-like safe transfer that rely on ERC1363 checks when
targeting contracts.
When the recipient address (to) has no code (i.e. is an EOA), this function behaves as forceApprove.
Oppositely, when the recipient address (to) has code, this function only attempts to call ERC1363.approveAndCall
once without retrying, and relies on the returned value to be true.
|
Reverts if the returned value is other than true.
ERC1363Utils
import "@openzeppelin/contracts/token/ERC20/utils/ERC1363Utils.sol";
Library that provides common ERC-1363 utility functions.
See ERC-1363.
checkOnERC1363TransferReceived(address operator, address from, address to, uint256 value, bytes data) internal
Performs a call to IERC1363Receiver.onTransferReceived on a target address.
Requirements:
-
The target has code (i.e. is a contract).
-
The target
tomust implement theIERC1363Receiverinterface. -
The target must return the
IERC1363Receiver.onTransferReceivedselector to accept the transfer.
checkOnERC1363ApprovalReceived(address operator, address spender, uint256 value, bytes data) internal
Performs a call to IERC1363Spender.onApprovalReceived on a target address.
Requirements:
-
The target has code (i.e. is a contract).
-
The target
spendermust implement theIERC1363Spenderinterface. -
The target must return the
IERC1363Spender.onApprovalReceivedselector to accept the approval.