// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import {
IERC7540,
IERC165,
IERC7540Redeem,
IERC7540Deposit
} from "./interfaces/IERC7540.sol";
import { ERC7540Receiver } from "./interfaces/ERC7540Receiver.sol";
import { IERC20, SafeERC20, Math, PermitParams } from "./SyncVault.sol";
import { SyncVault } from "./SyncVault.sol";
/**
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@%=::::::=%@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@*=#=--=*=*@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@:*= =#:@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@:@@ @@:@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@:@@ @@:@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@:@@ @@:@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@*-. .-*@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@* *@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@. .@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@* Amphor *@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@*==========#@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@+==========*@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@* Async *@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@% Vault %@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@= +@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@% %@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@= =@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@% .@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@= =@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@%----%@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@%+:::::+%@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@########@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*
* d8888 888
* d88888 888
* d88P888 888
* d88P 888 88888b.d88b. 88888b. 88888b. .d88b. 888d888
* d88P 888 888 "888 "88b 888 "88b 888 "88b d88""88b 888P"
* d88P 888 888 888 888 888 888 888 888 888 888 888
* d8888888888 888 888 888 888 d88P 888 888 Y88..88P 888
* d88P 888 888 888 888 88888P" 888 888 "Y88P" 888.io
* 888
* 888
* 888
*/
/**
* @dev This constant is used to divide the fees by 10_000 to get the percentage
* of the fees.
*/
uint256 constant BPS_DIVIDER = 10_000;
/*
* ########
* # LIBS #
* ########
*/
using Math for uint256; // only used for `mulDiv` operations.
using SafeERC20 for IERC20; // `safeTransfer` and `safeTransferFrom`
/**
* @title AsyncVault
* @dev This structure contains all the informations needed to let user claim
* their request after we processed those. To avoid rounding errors we store the
* totalSupply and totalAssets at the time of the deposit/redeem for the deposit
* and the redeem. We also store the amount of assets and shares given by the
* user.
*/
struct EpochData {
uint256 totalSupplySnapshot;
uint256 totalAssetsSnapshot;
mapping(address => uint256) depositRequestBalance;
mapping(address => uint256) redeemRequestBalance;
}
/**
* @title SettleValues
* @dev Hold the required values to settle the vault deposit and
* redeem requests.
*/
struct SettleValues {
uint256 lastSavedBalance;
uint256 fees;
uint256 pendingRedeem;
uint256 sharesToMint;
uint256 pendingDeposit;
uint256 assetsToWithdraw;
uint256 totalAssetsSnapshot;
uint256 totalSupplySnapshot;
}
/**
* @title Silo
* @dev This contract is used to hold the assets/shares of the users that
* requested a deposit/redeem. It is used to simplify the logic of the vault.
*/
contract Silo {
constructor(IERC20 underlying) {
underlying.forceApprove(msg.sender, type(uint256).max);
}
}
contract AsyncVault is IERC7540, SyncVault {
/*
* ####################################
* # AMPHOR SYNTHETIC RELATED STORAGE #
* ####################################
*/
/**
* @notice The epochId is used to keep track of the deposit and redeem
* requests. It is incremented every time the owner calls the `settle`
* function.
*/
uint256 public epochId;
/**
* @notice The treasury is used to store the address of the treasury.
* The treasury is used to store the fees taken from the vault.
* The treasury can be the owner of the contract or a specific address.
* The treasury can be changed by the owner of the contract.
* The treasury can be used to store the fees taken from the vault.
* The treasury can be the owner of the contract or a specific address.
*/
address public treasury;
/**
* @notice The lastSavedBalance is used to keep track of the assets in the
* vault at the time of the last `settle` call.
*/
Silo public pendingSilo;
/**
* @notice The claimableSilo is used to hold the assets/shares of the users
* that requested a deposit/redeem.
*/
Silo public claimableSilo;
/**
* @notice The epochs mapping is used to store the informations needed to
* let user claim their request after we processed those. To avoid rounding
* errors we store the totalSupply and totalAssets at the time of the
* deposit/redeem for the deposit and the redeem. We also store the amount
* of assets and shares given by the user.
*/
mapping(uint256 epochId => EpochData epoch) public epochs;
/**
* @notice The lastDepositRequestId is used to keep track of the last
* deposit
* request made by the user. It is used to let the user claim their request
* after we processed those.
*/
mapping(address user => uint256 epochId) public lastDepositRequestId;
/**
* @notice The lastRedeemRequestId is used to keep track of the last redeem
* request made by the user. It is used to let the user claim their request
* after we processed those.
*/
mapping(address user => uint256 epochId) public lastRedeemRequestId;
/*
* ##########
* # EVENTS #
* ##########
*/
/**
* @notice This event is emitted when a user request a deposit.
* @param requestId The id of the request.
* @param owner The address of the user that requested the deposit.
* @param previousRequestedAssets The amount of assets requested by the user
* before the new request.
* @param newRequestedAssets The amount of assets requested by the user.
*/
event DecreaseDepositRequest(
uint256 indexed requestId,
address indexed owner,
uint256 indexed previousRequestedAssets,
uint256 newRequestedAssets
);
/**
* @notice This event is emitted when a user request a redeem.
* @param requestId The id of the request.
* @param owner The address of the user that requested the redeem.
* @param previousRequestedShares The amount of shares requested by the user
* before the new request.
* @param newRequestedShares The amount of shares requested by the user.
*/
event DecreaseRedeemRequest(
uint256 indexed requestId,
address indexed owner,
uint256 indexed previousRequestedShares,
uint256 newRequestedShares
);
/**
* @notice This event is emitted when a user request a redeem.
* @param requestId The id of the request.
* @param owner The address of the user that requested the redeem.
* @param receiver The amount of shares requested by the user
* before the new request.
* @param assets The amount of shares requested by the user.
* @param shares The amount of shares requested by the user.
*/
event ClaimDeposit(
uint256 indexed requestId,
address indexed owner,
address indexed receiver,
uint256 assets,
uint256 shares
);
/**
* @notice This event is emitted when a user request a redeem.
* @param requestId The id of the request.
* @param owner The address of the user that requested the redeem.
* @param receiver The amount of shares requested by the user
* before the new request.
* @param assets The amount of shares requested by the user.
* @param shares The amount of shares requested by the user.
*/
event ClaimRedeem(
uint256 indexed requestId,
address indexed owner,
address indexed receiver,
uint256 assets,
uint256 shares
);
/*
* ##########
* # ERRORS #
* ##########
*/
/**
* @notice This error is emitted when the user request more shares than the
* maximum allowed.
* @param receiver The address of the user that requested the redeem.
* @param shares The amount of shares requested by the user.
*/
error ExceededMaxRedeemRequest(
address receiver, uint256 shares, uint256 maxShares
);
/**
* @notice This error is emitted when the user request more assets than the
* maximum allowed.
* @param receiver The address of the user that requested the deposit.
* @param assets The amount of assets requested by the user.
* @param maxDeposit The maximum amount of assets the user can request.
*/
error ExceededMaxDepositRequest(
address receiver, uint256 assets, uint256 maxDeposit
);
/**
* @notice This error is emitted when the user try to make a new request
* with an incorrect data.
*/
error ReceiverFailed();
/**
* @notice This error is emitted when the user try to make a new request
* on behalf of someone else.
*/
error ERC7540CantRequestDepositOnBehalfOf();
/**
* @notice This error is emitted when the user try to make a request
* when there is no claimable request available.
*/
error NoClaimAvailable(address owner);
/**
* @notice This error is emitted when the user try to make a request
* when the vault is open.
*/
error InvalidTreasury();
/*
* ##############################
* # AMPHOR SYNTHETIC FUNCTIONS #
* ##############################
*/
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() SyncVault() {
_disableInitializers();
}
function initialize(
uint16 fees,
address owner,
address _treasury,
IERC20 underlying,
uint256 bootstrapAmount,
string memory name,
string memory symbol
)
public
initializer
{
super.initialize(fees, owner, underlying, bootstrapAmount, name, symbol);
epochId = 1;
setTreasury(_treasury);
pendingSilo = new Silo(underlying);
claimableSilo = new Silo(underlying);
}
/**
* @dev This function is used to decrease the amount of assets requested to
* deposit by the user. It can only be called by the user who made the
* request.
* @param assets The amount of assets requested by the user.
*/
function decreaseDepositRequest(uint256 assets)
external
whenClosed
whenNotPaused
{
address owner = _msgSender();
uint256 oldBalance = epochs[epochId].depositRequestBalance[owner];
epochs[epochId].depositRequestBalance[owner] -= assets;
_asset.safeTransferFrom(address(pendingSilo), owner, assets);
emit DecreaseDepositRequest(
epochId,
owner,
oldBalance,
epochs[epochId].depositRequestBalance[owner]
);
}
/**
* @dev This function is used to decrease the amount of shares requested to
* redeem by the user. It can only be called by the user who made the
* request.
* @param shares The amount of shares requested by the user.
*/
function decreaseRedeemRequest(uint256 shares)
external
whenClosed
whenNotPaused
{
address owner = _msgSender();
uint256 oldBalance = epochs[epochId].redeemRequestBalance[owner];
epochs[epochId].redeemRequestBalance[owner] -= shares;
_update(address(pendingSilo), owner, shares);
emit DecreaseRedeemRequest(
epochId,
owner,
oldBalance,
epochs[epochId].redeemRequestBalance[owner]
);
}
/*
* ######################################
* # AMPHOR SYNTHETIC RELATED FUNCTIONS #
* ######################################
*/
/**
* @dev The `setTreasury` function is used to set the treasury address.
* It can only be called by the owner of the contract (`onlyOwner`
* modifier).
* @param _treasury The address of the treasury.
*/
function setTreasury(address _treasury) public onlyOwner {
if (_treasury == address(0)) revert InvalidTreasury();
treasury = _treasury;
}
/**
* @dev The `close` function is used to close the vault.
* It can only be called by the owner of the contract (`onlyOwner`
* modifier).
*/
function close() external override onlyOwner {
if (!vaultIsOpen) revert VaultIsClosed();
if (totalAssets() == 0) revert VaultIsEmpty();
lastSavedBalance = totalAssets();
vaultIsOpen = false;
_asset.safeTransfer(owner(), lastSavedBalance);
emit EpochStart(block.timestamp, lastSavedBalance, totalSupply());
}
/**
* @dev The `open` function is used to open the vault.
* @notice The `open` function is used to end the lock period of the vault.
* It can only be called by the owner of the contract (`onlyOwner` modifier)
* and only when the vault is locked.
* If there are profits, the performance fees are taken and sent to the
* owner of the contract.
* @param assetReturned The underlying assets amount to be deposited into
* the vault.
*/
function open(uint256 assetReturned)
external
override
onlyOwner
whenNotPaused
whenClosed
{
(uint256 newBalance,) = _settle(assetReturned);
vaultIsOpen = true;
_asset.safeTransferFrom(owner(), address(this), newBalance);
}
/*
* #################################
* # Permit RELATED FUNCTIONS #
* #################################
*/
/**
* @dev The `settle` function is used to settle the vault.
* @notice The `settle` function is used to settle the vault. It can only be
* called by the owner of the contract (`onlyOwner` modifier).
* If there are profits, the performance fees are taken and sent to the
* owner of the contract.
* Since amphor strategies can be time sensitive, we must be able to switch
* epoch without needing to put all the funds back.
* Using _settle we can virtually put back the funds, check how much we owe
* to users that want to redeem and maybe take the extra funds from the
* deposit requests.
* @param newSavedBalance The underlying assets amount to be deposited into
* the vault.
*/
function settle(uint256 newSavedBalance)
external
onlyOwner
whenNotPaused
whenClosed
{
(uint256 _lastSavedBalance, uint256 totalSupply) =
_settle(newSavedBalance);
emit EpochStart(block.timestamp, _lastSavedBalance, totalSupply);
}
/**
* @dev pendingRedeemRequest is used to know how many shares are currently
* waiting to be redeemed for the user.
* @param owner The address of the user that requested the redeem.
*/
function pendingRedeemRequest(address owner)
external
view
returns (uint256)
{
return epochs[epochId].redeemRequestBalance[owner];
}
/**
* @dev How many shares are virtually waiting for the user to be redeemed
* via the `claimRedeem` function.
* @param owner The address of the user that requested the redeem.
*/
function claimableRedeemRequest(address owner)
external
view
returns (uint256)
{
uint256 lastRequestId = lastRedeemRequestId[owner];
return isCurrentEpoch(lastRequestId)
? 0
: epochs[lastRequestId].redeemRequestBalance[owner];
}
/**
* @dev How many assets are currently waiting to be deposited for the user.
* @param owner The address of the user that requested the deposit.
*/
function pendingDepositRequest(address owner)
external
view
returns (uint256 assets)
{
return epochs[epochId].depositRequestBalance[owner];
}
/**
* @dev How many assets are virtually waiting for the user to be deposit
* via the `claimDeposit` function.
* @param owner The address of the user that requested the deposit.
*/
function claimableDepositRequest(address owner)
external
view
returns (uint256 assets)
{
uint256 lastRequestId = lastDepositRequestId[owner];
return isCurrentEpoch(lastRequestId)
? 0
: epochs[lastRequestId].depositRequestBalance[owner];
}
/**
* @dev How many assets are currently waiting to be deposited for all users.
* @return The amount of assets waiting to be deposited.
*/
function totalPendingDeposits() external view returns (uint256) {
return vaultIsOpen ? 0 : _asset.balanceOf(address(pendingSilo));
}
/**
* @dev How many shares are waiting to be redeemed for all users.
* @return The amount of shares waiting to be redeemed.
*/
function totalPendingRedeems() external view returns (uint256) {
return vaultIsOpen ? 0 : balanceOf(address(pendingSilo));
}
/**
* @dev How many shares are virtually waiting for the user to be redeemed
* via the `claimRedeem` function.
* @return The amount of shares waiting to be redeemed.
*/
function totalClaimableShares() external view returns (uint256) {
return balanceOf(address(claimableSilo));
}
/**
* @dev How many assets are virtually waiting for the user to be deposit
* via the `claimDeposit` function.
* @return The amount of assets waiting to be deposited.
*/
function totalClaimableAssets() external view returns (uint256) {
return _asset.balanceOf(address(claimableSilo));
}
/**
* @dev when the vault is closed, users can only request to deposit.
* By doing this funds will be sent and wait in the pendingSilo.
* When the owner will call the `open` or `settle` function, the funds will
* be deposited and the minted shares will be sent to the claimableSilo.
* Waiting for the users to claim them.
* @param assets The amount of assets requested by the user.
* @param receiver The address of the user that requested the deposit.
* @param owner The address of the user that requested the deposit.
* @param data The data to be sent to the receiver.
*/
function requestDeposit(
uint256 assets,
address receiver,
address owner,
bytes memory data
)
public
whenNotPaused
whenClosed
{
// vault
if (_msgSender() != owner) {
revert ERC7540CantRequestDepositOnBehalfOf();
}
if (previewClaimDeposit(receiver) > 0) {
_claimDeposit(receiver, receiver);
}
if (assets > maxDepositRequest(owner)) {
revert ExceededMaxDepositRequest(
receiver, assets, maxDepositRequest(owner)
);
}
_asset.safeTransferFrom(owner, address(pendingSilo), assets);
_createDepositRequest(assets, receiver, owner, data);
}
/**
* @dev when the vault is closed, users can only request to redeem.
* By doing this shares will be sent and wait in the pendingSilo.
* When the owner will call the `open` or `settle` function, the shares will
* be redeemed and the assets will be sent to the claimableSilo. Waiting for
* the users to claim them.
* @param shares The amount of shares requested by the user.
* @param receiver The address of the user that requested the redeem.
* @param owner The address of the user that requested the redeem.
* @param data The data to be sent to the receiver.
*/
function requestRedeem(
uint256 shares,
address receiver,
address owner,
bytes memory data
)
public
whenNotPaused
whenClosed
{
if (_msgSender() != owner) {
_spendAllowance(owner, _msgSender(), shares);
}
if (previewClaimRedeem(receiver) > 0) {
_claimRedeem(receiver, receiver);
}
if (shares > maxRedeemRequest(owner)) {
revert ExceededMaxRedeemRequest(
receiver, shares, maxRedeemRequest(owner)
);
}
_update(owner, address(pendingSilo), shares);
// Create a new request
_createRedeemRequest(shares, receiver, owner, data);
}
/**
* @dev This function let users claim the shares we owe them after we
* processed their deposit request, in the _settle function.
* @param receiver The address of the user that requested the deposit.
*/
function claimDeposit(address receiver)
public
whenNotPaused
returns (uint256 shares)
{
return _claimDeposit(_msgSender(), receiver);
}
/**
* @dev This function let users claim the assets we owe them after we
* processed their redeem request, in the _settle function.
* @param receiver The address of the user that requested the redeem.
*/
function claimRedeem(address receiver)
public
whenNotPaused
returns (uint256 assets)
{
return _claimRedeem(_msgSender(), receiver);
}
/**
* @dev This funciton let user request a deposit using permit signatures.
* @param assets The amount of assets requested by the user.
* @param receiver The address of the user that requested the deposit.
* @param data The data to be sent to the receiver.
* @param permitParams The permit signature.
*/
function requestDepositWithPermit(
uint256 assets,
address receiver,
bytes memory data,
PermitParams calldata permitParams
)
public
{
address _msgSender = _msgSender();
if (_asset.allowance(_msgSender, address(this)) < assets) {
execPermit(_msgSender, address(this), permitParams);
}
return requestDeposit(assets, receiver, _msgSender, data);
}
/**
* @dev users can request deposit only when the vault is closed and not
* paused.
* @return The maximum amount of assets the user can request.
*/
function maxDepositRequest(address) public view returns (uint256) {
return vaultIsOpen || paused() ? 0 : type(uint256).max;
}
/**
* @dev users can request redeem only when the vault is closed and not
* paused.
* @param owner The address of the user that requested the redeem.
* @return The maximum amount of shares the user can request.
*/
function maxRedeemRequest(address owner) public view returns (uint256) {
return vaultIsOpen || paused() ? 0 : balanceOf(owner);
}
/**
* @dev This function let users preview how many shares they will get if
* they claim their deposit request.
* @param owner The address of the user that requested the deposit.
* @return The amount of shares the user will get if they claim their
* deposit request.
* @notice This function let users preview how many shares they will get if
* they claim their deposit request.
*/
function previewClaimDeposit(address owner) public view returns (uint256) {
uint256 lastRequestId = lastDepositRequestId[owner];
uint256 assets = epochs[lastRequestId].depositRequestBalance[owner];
return _convertToShares(assets, lastRequestId, Math.Rounding.Floor);
}
/**
* @dev This function let users preview how many assets they will get if
* they claim their redeem request.
* @param owner The address of the user that requested the redeem.
* @return The amount of assets the user will get if they claim their
* redeem request.
*/
function previewClaimRedeem(address owner) public view returns (uint256) {
uint256 lastRequestId = lastRedeemRequestId[owner];
uint256 shares = epochs[lastRequestId].redeemRequestBalance[owner];
return _convertToAssets(shares, lastRequestId, Math.Rounding.Floor);
}
/**
* @dev This function convertToShares is used to convert the assets into
* shares.
* @param assets The amount of assets to convert.
* @param _epochId The epoch id.
* @return The amount of shares.
*/
function convertToShares(
uint256 assets,
uint256 _epochId
)
public
view
returns (uint256)
{
return _convertToShares(assets, _epochId, Math.Rounding.Floor);
}
/**
* @dev This function convertToAssets is used to convert the shares into
* assets.
* @param shares The amount of shares to convert.
* @param _epochId The epoch id.
* @return The amount of assets.
*/
function convertToAssets(
uint256 shares,
uint256 _epochId
)
public
view
returns (uint256)
{
return _convertToAssets(shares, _epochId, Math.Rounding.Floor);
}
/**
* Utils function to convert the shares claimable into assets. It can
* be used in the front end to save an rpc call.
*/
/**
* @dev This function claimableDepositBalanceInAsset is used to know if the
* owner will have to send money to the claimableSilo (for users who want to
* leave the vault) or if he will receive money from it.
* @notice Using this the owner can know if he will have to send money to
* the
* claimableSilo (for users who want to leave the vault) or if he will
* receive money from it.
* @param owner The address of the user that requested the deposit.
* @return The amount of assets the user will get if they claim their
* deposit request.
*/
function claimableDepositBalanceInAsset(address owner)
public
view
returns (uint256)
{
uint256 shares = previewClaimDeposit(owner);
return convertToAssets(shares);
}
/**
* @dev This function claimableRedeemBalanceInAsset is used to know if the
* owner will have to send money to the claimableSilo (for users who want to
* leave the vault) or if he will receive money from it.
* @param newSavedBalance The underlying assets amount to be deposited into
* the vault.
* @return assetsToOwner The amount of assets the
* user will get if they claim their redeem request.
* @return assetsToVault The amount of assets the user will get if
* they claim their redeem request.
* @return expectedAssetFromOwner The amount of assets that will be taken
* from the owner.
* @return settleValues The settle values.
*/
function previewSettle(uint256 newSavedBalance)
public
view
returns (
uint256 assetsToOwner,
uint256 assetsToVault,
uint256 expectedAssetFromOwner,
SettleValues memory settleValues
)
{
uint256 _lastSavedBalance = lastSavedBalance;
_checkMaxDrawdown(_lastSavedBalance, newSavedBalance);
// calculate the fees between lastSavedBalance and newSavedBalance
uint256 fees = _computeFees(_lastSavedBalance, newSavedBalance);
uint256 totalSupply = totalSupply();
// taking fees if positive yield
_lastSavedBalance = newSavedBalance - fees;
address pendingSiloAddr = address(pendingSilo);
uint256 pendingRedeem = balanceOf(pendingSiloAddr);
uint256 pendingDeposit = _asset.balanceOf(pendingSiloAddr);
uint256 sharesToMint = pendingDeposit.mulDiv(
totalSupply + 1, _lastSavedBalance + 1, Math.Rounding.Floor
);
uint256 totalAssetsSnapshot = _lastSavedBalance;
uint256 totalSupplySnapshot = totalSupply;
uint256 assetsToWithdraw = pendingRedeem.mulDiv(
_lastSavedBalance + pendingDeposit + 1,
totalSupply + sharesToMint + 1,
Math.Rounding.Floor
);
settleValues = SettleValues({
lastSavedBalance: _lastSavedBalance + fees,
fees: fees,
pendingRedeem: pendingRedeem,
sharesToMint: sharesToMint,
pendingDeposit: pendingDeposit,
assetsToWithdraw: assetsToWithdraw,
totalAssetsSnapshot: totalAssetsSnapshot,
totalSupplySnapshot: totalSupplySnapshot
});
if (pendingDeposit > assetsToWithdraw) {
assetsToOwner = pendingDeposit - assetsToWithdraw;
} else if (pendingDeposit < assetsToWithdraw) {
assetsToVault = assetsToWithdraw - pendingDeposit;
}
expectedAssetFromOwner = fees + assetsToVault;
}
/**
* @dev see EIP
* @param interfaceId The interface id to check for.
* @return True if the contract implements the interface.
*/
function supportsInterface(bytes4 interfaceId) public pure returns (bool) {
return interfaceId == type(IERC165).interfaceId
|| interfaceId == type(IERC7540Redeem).interfaceId
|| interfaceId == type(IERC7540Deposit).interfaceId;
}
// transfer must happen before this function is called
/**
* @dev _createDepositRequest is used to update the balance of the user in
* order to create the deposit request.
* @param assets The amount of assets requested by the user.
* @param receiver The address of the user that requested the deposit.
* @param owner The address of the user that requested the deposit.
*/
function _createDepositRequest(
uint256 assets,
address receiver,
address owner,
bytes memory data
)
internal
{
epochs[epochId].depositRequestBalance[receiver] += assets;
if (lastDepositRequestId[receiver] != epochId) {
lastDepositRequestId[receiver] = epochId;
}
if (
data.length > 0
&& ERC7540Receiver(receiver).onERC7540DepositReceived(
_msgSender(), owner, epochId, assets, data
) != ERC7540Receiver.onERC7540DepositReceived.selector
) revert ReceiverFailed();
emit DepositRequest(receiver, owner, epochId, _msgSender(), assets);
}
/**
* @dev _createRedeemRequest is used to update the balance of the user in
* order to create the redeem request.
* @param shares The amount of shares requested by the user.
* @param receiver The address of the user that requested the redeem.
* @param owner The address of the user that requested the redeem.
* @param data The data to be sent to the receiver.
* @notice This function is used to update the balance of the user.
*/
function _createRedeemRequest(
uint256 shares,
address receiver,
address owner,
bytes memory data
)
internal
{
epochs[epochId].redeemRequestBalance[receiver] += shares;
if (lastRedeemRequestId[receiver] != epochId) {
lastRedeemRequestId[receiver] = epochId;
}
if (
data.length > 0
&& ERC7540Receiver(receiver).onERC7540RedeemReceived(
_msgSender(), owner, epochId, shares, data
) != ERC7540Receiver.onERC7540RedeemReceived.selector
) revert ReceiverFailed();
emit RedeemRequest(receiver, owner, epochId, _msgSender(), shares);
}
/**
* @dev _claimDeposit is used to claim the pending deposit.
* @param owner The address of the user that requested the deposit.
* @param receiver The address of the user that requested the deposit.
* @return shares The amount of shares requested by the user.
*/
function _claimDeposit(
address owner,
address receiver
)
internal
returns (uint256 shares)
{
uint256 lastRequestId = lastDepositRequestId[owner];
if (lastRequestId == epochId) revert NoClaimAvailable(owner);
shares = previewClaimDeposit(owner);
uint256 assets = epochs[lastRequestId].depositRequestBalance[owner];
epochs[lastRequestId].depositRequestBalance[owner] = 0;
_update(address(claimableSilo), receiver, shares);
emit ClaimDeposit(lastRequestId, owner, receiver, assets, shares);
}
/**
* @dev _claimRedeem is used to claim the pending redeem and request a new
* one in one transaction.
* @param owner The address of the user that requested the redeem.
* @param receiver The address of the user that requested the redeem.
* @return assets The amount of assets requested by the user.
*/
function _claimRedeem(
address owner,
address receiver
)
internal
whenNotPaused
returns (uint256 assets)
{
uint256 lastRequestId = lastRedeemRequestId[owner];
if (lastRequestId == epochId) revert NoClaimAvailable(owner);
assets = previewClaimRedeem(owner);
uint256 shares = epochs[lastRequestId].redeemRequestBalance[owner];
epochs[lastRequestId].redeemRequestBalance[owner] = 0;
_asset.safeTransferFrom(address(claimableSilo), receiver, assets);
emit ClaimRedeem(lastRequestId, owner, receiver, assets, shares);
}
/**
* @dev _settle is used to settle the vault.
* @param newSavedBalance The underlying assets amount to be deposited into
* the vault.
* @return lastSavedBalance The last saved balance.
* @return totalSupply The total supply.
*/
function _settle(uint256 newSavedBalance)
internal
returns (uint256, uint256)
{
(
uint256 assetsToOwner,
uint256 assetsToVault,
,
SettleValues memory settleValues
) = previewSettle(newSavedBalance);
emit EpochEnd(
block.timestamp,
lastSavedBalance,
newSavedBalance,
settleValues.fees,
totalSupply()
);
_asset.safeTransferFrom(owner(), treasury, settleValues.fees);
// Settle the shares balance
_burn(address(pendingSilo), settleValues.pendingRedeem);
_mint(address(claimableSilo), settleValues.sharesToMint);
///////////////////////////
// Settle assets balance //
///////////////////////////
// either there are more deposits than withdrawals
if (settleValues.pendingDeposit > settleValues.assetsToWithdraw) {
_asset.safeTransferFrom(
address(pendingSilo), owner(), assetsToOwner
);
if (settleValues.assetsToWithdraw > 0) {
_asset.safeTransferFrom(
address(pendingSilo),
address(claimableSilo),
settleValues.assetsToWithdraw
);
}
} else if (settleValues.pendingDeposit < settleValues.assetsToWithdraw)
{
_asset.safeTransferFrom(
owner(), address(claimableSilo), assetsToVault
);
if (settleValues.pendingDeposit > 0) {
_asset.safeTransferFrom(
address(pendingSilo),
address(claimableSilo),
settleValues.pendingDeposit
);
}
} else if (settleValues.pendingDeposit > 0) {
// if _pendingDeposit == assetsToWithdraw AND _pendingDeposit > 0
// (and assetsToWithdraw > 0)
_asset.safeTransferFrom(
address(pendingSilo),
address(claimableSilo),
settleValues.assetsToWithdraw
);
}
emit Deposit(
address(pendingSilo),
address(claimableSilo),
settleValues.pendingDeposit,
settleValues.sharesToMint
);
emit Withdraw(
address(pendingSilo),
address(claimableSilo),
address(pendingSilo),
settleValues.assetsToWithdraw,
settleValues.pendingRedeem
);
settleValues.lastSavedBalance = settleValues.lastSavedBalance
- settleValues.fees + settleValues.pendingDeposit
- settleValues.assetsToWithdraw;
lastSavedBalance = settleValues.lastSavedBalance;
epochs[epochId].totalSupplySnapshot =
settleValues.totalSupplySnapshot;
epochs[epochId].totalAssetsSnapshot =
settleValues.totalAssetsSnapshot;
epochId++;
return (settleValues.lastSavedBalance, totalSupply());
}
/**
* @dev isCurrentEpoch is used to check if the request is the current epoch.
* @param requestId The id of the request.
*/
function isCurrentEpoch(uint256 requestId) internal view returns (bool) {
return requestId == epochId;
}
/**
* @dev _convertToShares is used to convert the assets into shares for a
* specific epoch/request.
* @param assets The amount of assets to convert.
* @param requestId The id of the request.
* @param rounding The rounding type.
*/
function _convertToShares(
uint256 assets,
uint256 requestId,
Math.Rounding rounding
)
internal
view
returns (uint256)
{
if (isCurrentEpoch(requestId)) return 0;
uint256 totalAssets = epochs[requestId].totalAssetsSnapshot + 1;
uint256 totalSupply = epochs[requestId].totalSupplySnapshot + 1;
return assets.mulDiv(totalSupply, totalAssets, rounding);
}
/**
* @dev _convertToAssets is used to convert the shares into assets for a
* specific epoch/request.
* @param shares The amount of shares to convert.
* @param requestId The id of the request.
* @param rounding The rounding type.
*/
function _convertToAssets(
uint256 shares,
uint256 requestId,
Math.Rounding rounding
)
internal
view
returns (uint256)
{
if (isCurrentEpoch(requestId)) return 0;
uint256 totalSupply = epochs[requestId].totalSupplySnapshot + 1;
uint256 totalAssets = epochs[requestId].totalAssetsSnapshot + 1;
return shares.mulDiv(totalAssets, totalSupply, rounding);
}
/**
* @dev _checkMaxDrawdown is used to check if the max drawdown is reached.
* @param _lastSavedBalance The last saved balance.
* @param newSavedBalance The new saved balance.
*/
function _checkMaxDrawdown(
uint256 _lastSavedBalance,
uint256 newSavedBalance
)
internal
view
{
if (
newSavedBalance
< _lastSavedBalance.mulDiv(
BPS_DIVIDER - _maxDrawdown, BPS_DIVIDER, Math.Rounding.Ceil
)
) revert MaxDrawdownReached();
}
function _computeFees(
uint256 _lastSavedBalance,
uint256 newSavedBalance
)
internal
view
returns (uint256 fees)
{
if (newSavedBalance > _lastSavedBalance && feesInBps > 0) {
uint256 profits;
unchecked {
profits = newSavedBalance - _lastSavedBalance;
}
fees = (profits).mulDiv(feesInBps, BPS_DIVIDER, Math.Rounding.Floor);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: By default this function reads _name which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Name() internal view returns (string memory) {
return _name.toStringWithFallback(_nameFallback);
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: By default this function reads _version which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Version() internal view returns (string memory) {
return _version.toStringWithFallback(_versionFallback);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
EIP712Storage storage $ = _getEIP712Storage();
$._name = name;
$._version = version;
// Reset prior values in storage if upgrading
$._hashedName = 0;
$._hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
EIP712Storage storage $ = _getEIP712Storage();
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = $._hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = $._hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev 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}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[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 ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev 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.
*
* NOTE: 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}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev 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.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev 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.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev 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.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev 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.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev 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:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set 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}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev 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.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Pausable.sol)
pragma solidity ^0.8.20;
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {PausableUpgradeable} from "../../../utils/PausableUpgradeable.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC20 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.
*
* IMPORTANT: 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.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {ERC20-_update}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _update(address from, address to, uint256 value) internal virtual override whenNotPaused {
super._update(from, to, value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 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.
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev 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 ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
return super.nonces(owner);
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712Upgradeable} from "../../../utils/cryptography/EIP712Upgradeable.sol";
import {NoncesUpgradeable} from "../../../utils/NoncesUpgradeable.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 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.
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20Permit, EIP712Upgradeable, NoncesUpgradeable {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev 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 ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override(IERC20Permit, NoncesUpgradeable) returns (uint256) {
return super.nonces(owner);
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev 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}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[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 ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev 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.
*
* NOTE: 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}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev 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.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev 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.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev 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.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev 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.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev 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:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set 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}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev 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.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.21;
interface ERC7540Receiver {
function onERC7540DepositReceived(
address operator,
address owner,
uint256 requestId,
uint256 assets,
bytes memory data
)
external
returns (bytes4);
function onERC7540RedeemReceived(
address operator,
address owner,
uint256 requestId,
uint256 shares,
bytes memory data
)
external
returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev 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.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev 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.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev 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.
*
* IMPORTANT: 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.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev 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.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 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:
*
* ```solidity
* 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.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev 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.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev 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.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev 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.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev 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.
*
* NOTE: 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.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev 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.
*
* NOTE: 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.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev 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.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev 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.
*
* NOTE: 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.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of 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
* 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).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev 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.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev 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.
*
* NOTE: 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.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of 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).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev 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.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev 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.
*
* NOTE: 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.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev 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.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev 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.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption 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.
*
* NOTE: 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.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev 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).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.21;
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP
* section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
}
interface IERC7540Deposit {
event DepositRequest(
address indexed receiver,
address indexed owner,
uint256 indexed requestId,
address sender,
uint256 assets
);
/**
* @dev Transfers assets from msg.sender into the Vault and submits a
* Request for asynchronous deposit/mint.
*
* - MUST support ERC-20 approve / transferFrom on asset as a deposit
* Request flow.
* - MUST revert if all of assets cannot be requested for deposit/mint.
*
* NOTE: most implementations will require pre-approval of the Vault with
* the Vault's underlying asset token.
*/
function requestDeposit(
uint256 assets,
address receiver,
address owner,
bytes memory data
)
external;
/**
* @dev Returns the amount of requested assets in Pending state for the
* operator to deposit or mint.
*
* - MUST NOT include any assets in Claimable state for deposit or mint.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT revert unless due to integer overflow caused by an
* unreasonably large input.
*/
function pendingDepositRequest(address owner)
external
view
returns (uint256 assets);
}
interface IERC7540Redeem {
event RedeemRequest(
address indexed receiver,
address indexed owner,
uint256 indexed requestId,
address sender,
uint256 shares
);
/**
* @dev Assumes control of shares from owner and submits a Request for
* asynchronous redeem/withdraw.
*
* - MUST support a redeem Request flow where the control of shares is taken
* from owner directly
* where msg.sender has ERC-20 approval over the shares of owner.
* - MUST revert if all of shares cannot be requested for redeem / withdraw.
*/
function requestRedeem(
uint256 shares,
address operator,
address owner,
bytes memory data
)
external;
/**
* @dev Returns the amount of requested shares in Pending state for the
* operator to redeem or withdraw.
*
* - MUST NOT include any shares in Claimable state for redeem or withdraw.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT revert unless due to integer overflow caused by an
* unreasonably large input.
*/
function pendingRedeemRequest(address owner)
external
view
returns (uint256 shares);
}
/**
* @title IERC7540
* @dev Interface of the ERC7540 "Asynchronous Tokenized Vault Standard", as
* defined in
* https://github.com/ethereum/EIPs/blob/2e63f2096b0c7d8388458bb0a03a7ce0eb3422a4/EIPS/eip-7540.md[ERC-7540].
*/
interface IERC7540 is IERC7540Deposit, IERC7540Redeem, IERC4626, IERC165 { }
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract Nonces {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
mapping(address account => uint256) private _nonces;
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
return _nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return _nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract NoncesUpgradeable is Initializable {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
/// @custom:storage-location erc7201:openzeppelin.storage.Nonces
struct NoncesStorage {
mapping(address account => uint256) _nonces;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Nonces")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant NoncesStorageLocation = 0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00;
function _getNoncesStorage() private pure returns (NoncesStorage storage $) {
assembly {
$.slot := NoncesStorageLocation
}
}
function __Nonces_init() internal onlyInitializing {
}
function __Nonces_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
return $._nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return $._nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {OwnableUpgradeable} from "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step
struct Ownable2StepStorage {
address _pendingOwner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;
function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {
assembly {
$.slot := Ownable2StepStorageLocation
}
}
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
function __Ownable2Step_init() internal onlyInitializing {
}
function __Ownable2Step_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
return $._pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
$._pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
delete $._pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev 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.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev 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.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
/// @solidity memory-safe-assembly
assembly {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import { Ownable2StepUpgradeable } from
"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {
ERC20Upgradeable,
IERC20
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { IERC20Metadata } from
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { ERC20PermitUpgradeable } from
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import { ERC20PausableUpgradeable } from
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol";
import { SafeERC20 } from
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Initializable } from
"@openzeppelin/contracts/proxy/utils/Initializable.sol";
import { ERC20Permit } from
"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
/*
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@%=::::::=%@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@*=#=--=*=*@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@:*= =#:@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@:@@ @@:@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@:@@ @@:@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@:@@ @@:@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@*-. .-*@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@* *@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@. .@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@* Amphor *@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@*==========#@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@+==========*@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@* Sync *@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@% Vault %@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@= +@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@% %@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@= =@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@% .@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@= =@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@%----%@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@%+:::::+%@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@########@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*
* d8888 888
* d88888 888
* d88P888 888
* d88P 888 88888b.d88b. 88888b. 88888b. .d88b. 888d888
* d88P 888 888 "888 "88b 888 "88b 888 "88b d88""88b 888P"
* d88P 888 888 888 888 888 888 888 888 888 888 888
* d8888888888 888 888 888 888 d88P 888 888 Y88..88P 888
* d88P 888 888 888 888 88888P" 888 888 "Y88P" 888.io
* 888
* 888
* 888
*/
/*
* ########
* # LIBS #
* ########
*/
using Math for uint256; // only used for `mulDiv` operations.
using SafeERC20 for IERC20; // `safeTransfer` and `safeTransferFrom`
struct PermitParams {
uint256 value;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
uint16 constant MAX_FEES = 3000; // 30%
abstract contract SyncVault is
IERC4626,
Ownable2StepUpgradeable,
ERC20PermitUpgradeable,
ERC20PausableUpgradeable
{
/*
* ####################################
* # AMPHOR SYNTHETIC RELATED STORAGE #
* ####################################
*/
// @return Amount of the perf fees applied on the positive yield.
uint16 public feesInBps;
uint16 internal _maxDrawdown; // guardrail
uint8 private _underlyingDecimals;
IERC20 internal _asset; // underlying asset
bool public vaultIsOpen; // vault is open or closed
uint256 public lastSavedBalance; // last saved balance
/*
* ##########
* # EVENTS #
* ##########
*/
event EpochStart(
uint256 indexed timestamp, uint256 lastSavedBalance, uint256 totalShares
);
event EpochEnd(
uint256 indexed timestamp,
uint256 lastSavedBalance,
uint256 returnedAssets,
uint256 fees,
uint256 totalShares
);
event FeesChanged(uint16 oldFees, uint16 newFees);
/*
* ##########
* # ERRORS #
* ##########
*/
error VaultIsClosed();
error VaultIsOpen();
error FeesTooHigh();
error ERC4626ExceededMaxDeposit(
address receiver, uint256 assets, uint256 max
);
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
error VaultIsEmpty(); // We cannot start an epoch with an empty vault
error MaxDrawdownReached();
error PermitFailed(); // see
// https://dedaub.com/blog/phantom-functions-and-the-billion-dollar-no-op
/*
* ##############################
* # AMPHOR SYNTHETIC FUNCTIONS #
* ##############################
*/
modifier whenClosed() {
if (vaultIsOpen) revert VaultIsOpen();
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
uint16 fees,
address owner,
IERC20 underlying,
uint256 bootstrapAmount,
string memory name,
string memory symbol
)
public
virtual
onlyInitializing
{
if (fees > MAX_FEES) revert FeesTooHigh();
feesInBps = fees;
vaultIsOpen = true;
_maxDrawdown = 3000; // 30%
_asset = underlying;
_underlyingDecimals =
uint8(IERC20Metadata(address(underlying)).decimals());
__ERC20_init(name, symbol);
__Ownable_init(owner);
__ERC20Permit_init(name);
__ERC20Pausable_init();
deposit(bootstrapAmount, owner);
}
/**
* @dev The `withdraw` function is used to withdraw the specified underlying
* assets amount in exchange of a proportional amount of shares.
* @param assets The underlying assets amount to be converted into shares.
* @param receiver The address of the shares receiver.
* @param owner The address of the owner.
* @return Amount of shares received in exchange of the specified underlying
* assets amount.
*/
function withdraw(
uint256 assets,
address receiver,
address owner
)
external
whenNotPaused
returns (uint256)
{
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 sharesAmount = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, sharesAmount);
return sharesAmount;
}
/*
* #################################
* # Pausability RELATED FUNCTIONS #
* #################################
*/
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
/*
* ######################################
* # AMPHOR SYNTHETIC RELATED FUNCTIONS #
* ######################################
*/
/**
* @dev The `setFee` function is used to modify the protocol fees.
* @notice The `setFee` function is used to modify the perf fees.
* It can only be called by the owner of the contract (`onlyOwner`
* modifier).
* It can't exceed 30% (3000 in BPS).
* @param newFee The new perf fees to be applied.
*/
function setFee(uint16 newFee) external onlyOwner {
if (!vaultIsOpen) revert VaultIsClosed();
if (newFee > MAX_FEES) revert FeesTooHigh();
feesInBps = newFee;
emit FeesChanged(feesInBps, newFee);
}
function setMaxDrawdown(uint16 newMaxDrawdown) external onlyOwner {
if (newMaxDrawdown > 10_000) revert MaxDrawdownReached();
_maxDrawdown = newMaxDrawdown;
}
function open(uint256 assetReturned) external virtual;
function close() external virtual;
/*
* #################################
* # Permit RELATED FUNCTIONS #
* #################################
*/
/**
* @dev The `depositWithPermit` function is used to deposit underlying
* assets
* into the vault using a permit for approval.
* @param assets The underlying assets amount to be converted into
* shares.
* @param receiver The address of the shares receiver.
* @param permitParams The permit struct containing the permit signature and
* data.
* @return Amount of shares received in exchange of the specified underlying
* assets amount.
*/
function depositWithPermit(
uint256 assets,
address receiver,
PermitParams calldata permitParams
)
external
returns (uint256)
{
address _msgSender = _msgSender();
if (_asset.allowance(_msgSender, address(this)) < assets) {
execPermit(_msgSender, address(this), permitParams);
}
return deposit(assets, receiver);
}
/**
* @dev See {IERC4626-deposit}
* @notice The `deposit` function is used to deposit underlying assets into
* the vault.
* @param assets The underlying assets amount to be converted into shares.
* @param receiver The address of the shares receiver.
* @return Amount of shares received in exchange of the
* specified underlying assets amount.
*/
function deposit(
uint256 assets,
address receiver
)
public
whenNotPaused
returns (uint256)
{
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 sharesAmount = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, sharesAmount);
return sharesAmount;
}
/**
* @dev The `mint` function is used to mint the specified amount of shares
* in
* exchange of the corresponding assets amount from owner.
* @param shares The shares amount to be converted into underlying assets.
* @param receiver The address of the shares receiver.
* @return Amount of underlying assets deposited in exchange of the
* specified
* amount of shares.
*/
function mint(
uint256 shares,
address receiver
)
public
whenNotPaused
returns (uint256)
{
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assetsAmount = previewMint(shares);
_deposit(_msgSender(), receiver, assetsAmount, shares);
return assetsAmount;
}
/**
* @dev The `redeem` function is used to redeem the specified amount of
* shares in exchange of the corresponding underlying assets amount from
* owner.
* @param shares The shares amount to be converted into underlying assets.
* @param receiver The address of the shares receiver.
* @param owner The address of the owner.
* @return Amount of underlying assets received in exchange of the specified
* amount of shares.
*/
function redeem(
uint256 shares,
address receiver,
address owner
)
public
whenNotPaused
returns (uint256)
{
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assetsAmount = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assetsAmount, shares);
return assetsAmount;
}
// @return address of the underlying asset.
function asset() public view returns (address) {
return address(_asset);
}
// @dev See {IERC4626-convertToShares}.
function convertToShares(uint256 assets) public view returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
function sharesBalanceInAsset(address owner)
public
view
returns (uint256)
{
return convertToAssets(balanceOf(owner));
}
// @dev See {IERC4626-convertToAssets}.
function convertToAssets(uint256 shares) public view returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/*
* @dev The `maxDeposit` function is used to calculate the maximum deposit.
* @notice If the vault is locked or paused, users are not allowed to
* deposit,
* the maxDeposit is 0.
* @return Amount of the maximum underlying assets deposit amount.
*/
function maxDeposit(address) public view returns (uint256) {
return vaultIsOpen && !paused() ? type(uint256).max : 0;
}
/**
* @dev The `maxMint` function is used to calculate the maximum amount of
* shares you can mint.
* @notice If the vault is locked or paused, the maxMint is 0.
* @return Amount of the maximum shares mintable for the specified address.
*/
function maxMint(address) public view returns (uint256) {
return vaultIsOpen && !paused() ? type(uint256).max : 0;
}
/**
* @dev See {IERC4626-maxWithdraw}.
* @notice If the function is called during the lock period the maxWithdraw
* is `0`.
* @return Amount of the maximum number of withdrawable underlying assets.
*/
function maxWithdraw(address owner) public view returns (uint256) {
return vaultIsOpen && !paused()
? _convertToAssets(balanceOf(owner), Math.Rounding.Floor)
: 0;
}
/**
* @dev See {IERC4626-maxRedeem}.
* @notice If the function is called during the lock period the maxRedeem is
* `0`;
* @param owner The address of the owner.
* @return Amount of the maximum number of redeemable shares.
*/
function maxRedeem(address owner) public view returns (uint256) {
return vaultIsOpen && !paused() ? balanceOf(owner) : 0;
}
/**
* @dev See {IERC4626-previewDeposit}.
*/
function previewDeposit(uint256 assets) public view returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/**
* @dev See {IERC4626-previewMint}.
*/
function previewMint(uint256 shares) public view returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/**
* @dev See {IERC4626-previewWithdraw}
*/
function previewWithdraw(uint256 assets) public view returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/**
* @dev See {IERC4626-previewRedeem}
*/
function previewRedeem(uint256 shares) public view returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
function totalAssets() public view returns (uint256) {
if (vaultIsOpen) return _asset.balanceOf(address(this));
else return _asset.balanceOf(address(this)) + lastSavedBalance;
}
/**
* @dev The `_deposit` function is used to deposit the specified underlying
* assets amount in exchange of a proportionnal amount of shares.
* @param caller The address of the caller.
* @param receiver The address of the shares receiver.
* @param assets The underlying assets amount to be converted into shares.
* @param shares The shares amount to be converted into underlying assets.
*/
function _deposit(
address caller,
address receiver,
uint256 assets,
uint256 shares
)
internal
{
// If _asset is ERC777, transferFrom can trigger a reentrancy BEFORE the
// transfer happens through the tokensToSend hook. On the other hand,
// the tokenReceived hook, that is triggered after the transfer,calls
// the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any
// reentrancy would happen before the assets are transferred and before
// the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
_asset.safeTransferFrom(caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev The function `_withdraw` is used to withdraw the specified
* underlying assets amount in exchange of a proportionnal amount of shares
* by
* specifying all the params.
* @notice The `withdraw` function is used to withdraw the specified
* underlying assets amount in exchange of a proportionnal amount of shares.
* @param receiver The address of the shares receiver.
* @param owner The address of the owner.
* @param assets The underlying assets amount to be converted into shares.
* @param shares The shares amount to be converted into underlying assets.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
)
internal
{
if (caller != owner) _spendAllowance(owner, caller, shares);
_burn(owner, shares);
_asset.safeTransfer(receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _update(
address from,
address to,
uint256 value
)
internal
virtual
override(ERC20Upgradeable, ERC20PausableUpgradeable)
{
ERC20PausableUpgradeable._update(from, to, value);
}
function execPermit(
address owner,
address spender,
PermitParams calldata permitParams
)
internal
{
ERC20Permit(address(_asset)).permit(
owner,
spender,
permitParams.value,
permitParams.deadline,
permitParams.v,
permitParams.r,
permitParams.s
);
if (_asset.allowance(owner, spender) != permitParams.value) {
revert PermitFailed();
}
}
/**
* @dev Internal conversion function (from assets to shares) with support
* for rounding direction.
* @param assets Theunderlying assets amount to be converted into shares.
* @param rounding The rounding direction.
* @return Amount of shares received in exchange of the specified underlying
* assets amount.
*/
function _convertToShares(
uint256 assets,
Math.Rounding rounding
)
internal
view
returns (uint256)
{
return assets.mulDiv(totalSupply() + 1, totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support
* for rounding direction.
* @param shares The shares amount to be converted into underlying assets.
* @param rounding The rounding direction.
* @return Amount of underlying assets received in exchange of the
* specified amount of shares.
*/
function _convertToAssets(
uint256 shares,
Math.Rounding rounding
)
internal
view
returns (uint256)
{
return shares.mulDiv(totalAssets() + 1, totalSupply() + 1, rounding);
}
function decimals()
public
view
virtual
override(ERC20Upgradeable, IERC20Metadata)
returns (uint8)
{
return _underlyingDecimals;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import {
Ownable2Step,
Ownable
} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { SafeERC20 } from
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC7540, IERC4626 } from "./interfaces/IERC7540.sol";
import { PermitParams, AsyncVault } from "./AsyncVault.sol";
import { ERC20Permit } from
"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
contract VaultZapper is Ownable2Step, Pausable {
/**
* @dev The `SafeERC20` lib is only used for `safeTransfer`,
* `safeTransferFrom` and `forceApprove` operations.
*/
using SafeERC20 for IERC20;
/**
* @dev The `Address` lib is only used for `sendValue` operations.
*/
using Address for address payable;
/**
* @notice The `authorizedVaults` mapping is used to check if a vault is
* authorized to interact with the `VaultZapper` contract.
*/
mapping(IERC4626 vault => bool isAuthorized) public authorizedVaults;
/**
* @notice The `authorizedRouters` mapping is used to check if a router is
* authorized to interact with the `VaultZapper` contract.
*/
mapping(address routerAddress => bool isAuthorized) public authorizedRouters;
/**
* @dev The `ZapAndDeposit` event is emitted when a user zaps in and
* deposits
* assets into a vault.
*/
event ZapAndRequestDeposit(
IERC7540 indexed vault,
address indexed router,
IERC20 tokenIn,
uint256 amount
);
/**
* @dev The `ZapAndDeposit` event is emitted when a user zaps in and
* deposits
* assets into a vault.
*/
event ZapAndDeposit(
IERC4626 indexed vault,
address indexed router,
IERC20 tokenIn,
uint256 amount,
uint256 shares
);
/**
* @dev The `RouterApproved` event is emitted when a router is approved to
* interact with a token.
*/
event RouterApproved(address indexed router, IERC20 indexed token);
/**
* @dev The `RouterAuthorized` event is emitted when a router is authorized
* to interact with the `VaultZapper` contract.
*/
event RouterAuthorized(address indexed router, bool allowed);
/**
* @dev The `VaultAuthorized` event is emitted when a vault is authorized to
* interact with the `VaultZapper` contract.
*/
event VaultAuthorized(IERC4626 indexed vault, bool allowed);
/**
* @dev The `NotRouter` error is emitted when a router is not authorized to
* interact with the `VaultZapper` contract.
*/
error NotRouter(address router);
/**
* @dev The `NotVault` error is emitted when a vault is not authorized to
* interact with the `VaultZapper` contract.
*/
error NotVault(IERC4626 vault);
/**
* @dev The `SwapFailed` error is emitted when a swap fails.
*/
error SwapFailed(string reason);
/**
* @dev The `InconsistantSwapData` error is emitted when the swap data is
* inconsistant.
*/
error InconsistantSwapData(
uint256 expectedTokenInBalance, uint256 actualTokenInBalance
);
/**
* @dev The `NotEnoughSharesMinted` error is emitted when the amount of
* shares
* minted is not enough.
*/
error NotEnoughSharesMinted(uint256 sharesMinted, uint256 minSharesMinted);
/**
* @dev The `NotEnoughUnderlying` error is emitted when the amount of
* underlying assets is not enough.
*/
error NotEnoughUnderlying(
uint256 previewedUnderlying, uint256 withdrawedUnderlying
);
/**
* @dev The `NullMinShares` error is emitted when the minimum amount of
* shares
* to mint is null.
*/
error NullMinShares();
/**
* @dev See
* https://dedaub.com/blog/phantom-functions-and-the-billion-dollar-no-op
*/
error PermitFailed();
/**
* @dev The `onlyAllowedRouter` modifier is used to check if a router is
* authorized to interact with the `VaultZapper` contract.
*/
modifier onlyAllowedRouter(address router) {
if (!authorizedRouters[router]) revert NotRouter(router);
_;
}
/**
* @dev The `onlyAllowedVault` modifier is used to check if a vault is
* authorized to interact with the `VaultZapper` contract.
*/
modifier onlyAllowedVault(IERC4626 vault) {
if (!authorizedVaults[vault]) revert NotVault(vault);
_;
}
constructor() Ownable(_msgSender()) { }
/**
* @dev The `withdrawToken` function is used to withdraw tokens from the
* `VaultZapper` contract.
*/
function withdrawToken(IERC20 token) external onlyOwner {
token.safeTransfer(_msgSender(), token.balanceOf(address(this)));
}
/**
* @dev The `withdrawNativeToken` function is used to withdraw native tokens
* from the `VaultZapper` contract.
*/
function withdrawNativeToken() external onlyOwner {
payable(_msgSender()).sendValue(address(this).balance);
}
/**
* @dev The `pause` function is used to pause the `VaultZapper` contract.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev The `unpause` function is used to unpause the `VaultZapper`
* contract.
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @dev The `approveTokenForRouter` function is used to approve a token for
* a
* router.
*/
function approveTokenForRouter(
IERC20 token,
address router
)
public
onlyOwner
onlyAllowedRouter(router)
{
token.forceApprove(router, type(uint256).max);
emit RouterApproved(router, token);
}
/**
* @dev The `toggleRouterAuthorization` function is used to toggle the
* authorization of a router.
*/
function toggleRouterAuthorization(address router) public onlyOwner {
bool authorized = !authorizedRouters[router];
authorizedRouters[router] = authorized;
emit RouterAuthorized(router, authorized);
}
/**
* @dev The `toggleVaultAuthorization` function is used to toggle the
* authorization of a vault.
*/
function toggleVaultAuthorization(IERC7540 vault) public onlyOwner {
bool authorized = !authorizedVaults[vault];
IERC20(vault.asset()).forceApprove(
address(vault), authorized ? type(uint256).max : 0
);
authorizedVaults[vault] = authorized;
emit VaultAuthorized(vault, authorized);
}
/**
* @dev The `_zapIn` function is used to zap in assets into a vault.
*/
function _zapIn(
IERC20 tokenIn,
address router,
uint256 amount,
bytes calldata data
)
internal
{
uint256 expectedBalance; // of tokenIn (currently)
if (msg.value == 0) {
expectedBalance = tokenIn.balanceOf(address(this));
_transferTokenInAndApprove(router, tokenIn, amount);
} else {
expectedBalance = address(this).balance - msg.value;
}
_executeZap(router, data); // zap
uint256 balanceAfterZap = msg.value == 0
? tokenIn.balanceOf(address(this))
: address(this).balance;
if (balanceAfterZap > expectedBalance) {
// Our balance is higher than expected, we shouldn't have received
// any token
revert InconsistantSwapData({
expectedTokenInBalance: expectedBalance,
actualTokenInBalance: balanceAfterZap
});
}
}
/**
* @dev The `_transferTokenInAndApprove` function is used to transfer tokens
* into the `VaultZapper` contract and approve them for a router.
*/
function _transferTokenInAndApprove(
address router,
IERC20 tokenIn,
uint256 amount
)
internal
{
tokenIn.safeTransferFrom(_msgSender(), address(this), amount);
if (tokenIn.allowance(address(this), router) < amount) {
tokenIn.forceApprove(router, amount);
}
}
/*
########################
USER RELATED FUNCTIONS
########################
*/
/**
* @dev The `zapAndDeposit` function is used to zap in and deposit assets
* into a vault.
*/
function zapAndDeposit(
IERC20 tokenIn,
IERC4626 vault,
address router,
uint256 amount,
bytes calldata data
)
public
payable
onlyAllowedRouter(router)
onlyAllowedVault(vault)
whenNotPaused
returns (uint256)
{
uint256 initialTokenOutBalance =
IERC20(vault.asset()).balanceOf(address(this)); // tokenOut balance to
// deposit, not final value
// Zap
_zapIn(tokenIn, router, amount, data);
// Deposit
uint256 shares = vault.deposit(
IERC20(vault.asset()).balanceOf(address(this))
- initialTokenOutBalance,
_msgSender()
);
emit ZapAndDeposit({
vault: vault,
router: router,
tokenIn: tokenIn,
amount: amount,
shares: shares
});
return shares;
}
/**
* @dev The `zapAndRequestDeposit` function is used to zap in and request a
* deposit of assets into a vault.
*/
function zapAndRequestDeposit(
IERC20 tokenIn,
IERC7540 vault,
address router,
uint256 amountIn,
bytes calldata swapData,
bytes calldata callback7540Data
)
public
payable
onlyAllowedRouter(router)
onlyAllowedVault(vault)
whenNotPaused
{
uint256 initialTokenOutBalance =
IERC20(vault.asset()).balanceOf(address(this)); // tokenOut balance to
// deposit, not final value
// Zap
_zapIn(tokenIn, router, amountIn, swapData);
// Request deposit
vault.requestDeposit(
IERC20(vault.asset()).balanceOf(address(this))
- initialTokenOutBalance,
_msgSender(),
address(this),
callback7540Data
);
emit ZapAndRequestDeposit({
vault: vault,
router: router,
tokenIn: tokenIn,
amount: amountIn
});
}
/*
##########################
PERMIT RELATED FUNCTIONS
##########################
*/
/**
* @dev The `zapAndDepositWithPermit` function is used to zap in and deposit
* assets into a vault with a permit.
*/
function zapAndDepositWithPermit(
IERC20 tokenIn,
IERC4626 vault,
address router,
uint256 amount,
bytes calldata swapData,
PermitParams calldata permitParams
)
public
returns (uint256)
{
if (tokenIn.allowance(_msgSender(), address(this)) < amount) {
_execPermit(tokenIn, _msgSender(), address(this), permitParams);
}
return zapAndDeposit(tokenIn, vault, router, amount, swapData);
}
/**
* @dev The `zapAndRequestDepositWithPermit` function is used to zap in and
* request a deposit of assets into a vault with a permit.
*/
function zapAndRequestDepositWithPermit(
IERC20 tokenIn,
IERC7540 vault,
address router,
uint256 amount,
bytes calldata swapData,
PermitParams calldata permitParams,
bytes calldata callback7540Data
)
public
{
if (tokenIn.allowance(_msgSender(), address(this)) < amount) {
_execPermit(tokenIn, _msgSender(), address(this), permitParams);
}
zapAndRequestDeposit(
tokenIn, vault, router, amount, swapData, callback7540Data
);
}
/**
* @dev The `_executeZap` function is used to execute a zap.
*/
function _executeZap(
address target,
bytes memory data
)
internal
returns (bytes memory response)
{
(bool success, bytes memory _data) =
target.call{ value: msg.value }(data);
if (!success) {
if (data.length > 0) revert SwapFailed(string(_data));
else revert SwapFailed("Unknown reason");
}
return _data;
}
/**
* @dev The `_executePermit` function is used to execute a permit.
*/
function _execPermit(
IERC20 token,
address owner,
address spender,
PermitParams calldata permitParams
)
internal
{
ERC20Permit(address(token)).permit(
owner,
spender,
permitParams.value,
permitParams.deadline,
permitParams.v,
permitParams.r,
permitParams.s
);
if (token.allowance(owner, spender) != permitParams.value) {
revert PermitFailed();
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
{
"compilationTarget": {
"src/VaultZapper.sol": "VaultZapper"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 10000
},
"remappings": [
":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
":@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
":@src/=src/",
":@test/=test/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
":permit2/=lib/permit2/",
":solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
":solmate/=lib/permit2/lib/solmate/"
]
}
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"uint256","name":"expectedTokenInBalance","type":"uint256"},{"internalType":"uint256","name":"actualTokenInBalance","type":"uint256"}],"name":"InconsistantSwapData","type":"error"},{"inputs":[{"internalType":"uint256","name":"sharesMinted","type":"uint256"},{"internalType":"uint256","name":"minSharesMinted","type":"uint256"}],"name":"NotEnoughSharesMinted","type":"error"},{"inputs":[{"internalType":"uint256","name":"previewedUnderlying","type":"uint256"},{"internalType":"uint256","name":"withdrawedUnderlying","type":"uint256"}],"name":"NotEnoughUnderlying","type":"error"},{"inputs":[{"internalType":"address","name":"router","type":"address"}],"name":"NotRouter","type":"error"},{"inputs":[{"internalType":"contract IERC4626","name":"vault","type":"address"}],"name":"NotVault","type":"error"},{"inputs":[],"name":"NullMinShares","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"PermitFailed","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"string","name":"reason","type":"string"}],"name":"SwapFailed","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"router","type":"address"},{"indexed":true,"internalType":"contract IERC20","name":"token","type":"address"}],"name":"RouterApproved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"router","type":"address"},{"indexed":false,"internalType":"bool","name":"allowed","type":"bool"}],"name":"RouterAuthorized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC4626","name":"vault","type":"address"},{"indexed":false,"internalType":"bool","name":"allowed","type":"bool"}],"name":"VaultAuthorized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC4626","name":"vault","type":"address"},{"indexed":true,"internalType":"address","name":"router","type":"address"},{"indexed":false,"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"ZapAndDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC7540","name":"vault","type":"address"},{"indexed":true,"internalType":"address","name":"router","type":"address"},{"indexed":false,"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ZapAndRequestDeposit","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"address","name":"router","type":"address"}],"name":"approveTokenForRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"routerAddress","type":"address"}],"name":"authorizedRouters","outputs":[{"internalType":"bool","name":"isAuthorized","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC4626","name":"vault","type":"address"}],"name":"authorizedVaults","outputs":[{"internalType":"bool","name":"isAuthorized","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"router","type":"address"}],"name":"toggleRouterAuthorization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC7540","name":"vault","type":"address"}],"name":"toggleVaultAuthorization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"withdrawNativeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"token","type":"address"}],"name":"withdrawToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"contract IERC4626","name":"vault","type":"address"},{"internalType":"address","name":"router","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"zapAndDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"contract IERC4626","name":"vault","type":"address"},{"internalType":"address","name":"router","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct PermitParams","name":"permitParams","type":"tuple"}],"name":"zapAndDepositWithPermit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"contract IERC7540","name":"vault","type":"address"},{"internalType":"address","name":"router","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"internalType":"bytes","name":"callback7540Data","type":"bytes"}],"name":"zapAndRequestDeposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"contract IERC7540","name":"vault","type":"address"},{"internalType":"address","name":"router","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"components":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct PermitParams","name":"permitParams","type":"tuple"},{"internalType":"bytes","name":"callback7540Data","type":"bytes"}],"name":"zapAndRequestDepositWithPermit","outputs":[],"stateMutability":"nonpayable","type":"function"}]