Verified contractPartialBUSL-1.1
EthenaARM
Address0xebb2b66759b593ea50eb8c306e2e13464cdb99fe
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.23
- Same code
Only this contract
Details
- Compiler
- solc 0.8.23+commit.f704f362
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- shanghai
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,350,254
- Creation transaction
- 0x638c871532…30ccb7bed1
14 files
- src/contracts/EthenaARM.solmain2.86 KB
- dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/interfaces/IERC4626.sol12.18 KB
- dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/interfaces/draft-IERC6093.sol6.53 KB
- dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/utils/math/SafeCast.sol34.69 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/proxy/utils/Initializable.sol8.91 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/token/ERC20/ERC20Upgradeable.sol12.47 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/utils/ContextUpgradeable.sol1.19 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/utils/ReentrancyGuardUpgradeable.sol4.36 KB
- src/contracts/AbstractARM.sol61.49 KB
- src/contracts/Interfaces.sol12.57 KB
- src/contracts/Ownable.sol1.74 KB
- src/contracts/OwnableOperable.sol1.1 KB
src/contracts/EthenaARM.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {AbstractARM} from "./AbstractARM.sol";
/**
* @title Ethena sUSDe/USDe Automated Redemption Manager (ARM)
* @author Origin Protocol Inc
*/
contract EthenaARM is Initializable, AbstractARM {
/// @dev Deprecated cooldown amount retained for storage layout compatibility.
uint256 internal _deprecatedLiquidityAmountInCooldown;
/// @dev Deprecated unstaker helper array retained for storage layout compatibility.
address[42] internal _deprecatedUnstakers;
/// @dev Deprecated unstaker index retained for storage layout compatibility.
uint8 internal _deprecatedNextUnstakerIndex;
/// @dev Deprecated request timestamp retained for storage layout compatibility.
uint32 internal _deprecatedLastRequestTimestamp;
/// @param _usde The address of Ethena's synthetic dollar token (USDe)
/// @param _claimDelay The delay in seconds before a user can claim a redeem from the request
/// @param _minSharesToRedeem The minimum amount of shares to redeem from the active lending market
/// @param _allocateThreshold The minimum amount of liquidity assets in excess of the ARM buffer before
/// the ARM can allocate to a active lending market.
constructor(address _usde, uint256 _claimDelay, uint256 _minSharesToRedeem, int256 _allocateThreshold)
AbstractARM(_usde, _claimDelay, _minSharesToRedeem, _allocateThreshold)
{
_disableInitializers();
}
/// @notice Initialize the storage variables stored in the proxy contract.
/// The deployer that calls initialize has to approve the ARM's proxy contract to transfer 1e12 USDe.
/// @param _name The name of the liquidity provider (LP) token.
/// @param _symbol The symbol of the liquidity provider (LP) token.
/// @param _operator The address of the account that can request and claim withdrawals.
/// @param _fee The fee accrued on discounted base-asset buy swaps measured in basis points (1/100th of a percent).
/// 10,000 = 100% fee
/// 500 = 5% fee
/// @param _feeCollector The account that can collect the accrued swap fee
/// @param _capManager The address of the CapManager contract
function initialize(
string calldata _name,
string calldata _symbol,
address _operator,
uint256 _fee,
address _feeCollector,
address _capManager
) external initializer {
_initARM(_operator, _name, _symbol, _fee, _feeCollector, _capManager);
}
/// @dev Revert if legacy Ethena cooldowns are still outstanding.
function checkNoLegacyWithdrawQueue() external view {
require(_deprecatedLiquidityAmountInCooldown == 0, "Legacy Ethena cooldown pending");
}
}
dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/interfaces/IERC4626.sol
// 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);
}
dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/interfaces/draft-IERC6093.sol
// 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);
}
dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/token/ERC20/IERC20.sol
// 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);
}
dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/token/ERC20/extensions/IERC20Metadata.sol
// 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);
}
dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
}
dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/proxy/utils/Initializable.sol
// 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
}
}
}
dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/token/ERC20/ERC20Upgradeable.sol
// 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);
}
}
}
}
dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/utils/ContextUpgradeable.sol
// 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;
}
}
dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
src/contracts/AbstractARM.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {OwnableOperable} from "./OwnableOperable.sol";
import {IAssetAdapter, IERC20, ICapManager} from "./Interfaces.sol";
/**
* @title Generic Automated Redemption Manager (ARM)
* @notice Coordinates liquidity-provider shares, two-token swaps, active market allocation, and
* protocol-specific redemption adapters for one liquidity asset and one or more supported base assets.
* @dev Existing ARM proxies depend on the original storage prefix. New multi-base state is appended after
* legacy single-base storage so Lido, EtherFi, Ethena, and Origin ARMs can share this implementation.
* @author Origin Protocol Inc
*/
abstract contract AbstractARM is OwnableOperable, ERC20Upgradeable, ReentrancyGuardUpgradeable {
////////////////////////////////////////////////////
/// Constants
////////////////////////////////////////////////////
/// @notice Maximum amount the Owner can set the cross price below 1 scaled to 36 decimals.
/// 20e32 is a 0.2% deviation, or 20 basis points.
uint256 internal constant MAX_CROSS_PRICE_DEVIATION = 20e32;
/// @notice Scale used for prices.
uint256 internal constant PRICE_SCALE = 1e36;
/// @notice The amount of shares minted to a dead address on initialization.
uint256 internal constant MIN_TOTAL_SUPPLY = 1e12;
/// @notice Address with no known private key that receives initial dead shares.
address internal constant DEAD_ACCOUNT = 0x000000000000000000000000000000000000dEaD;
/// @notice Scale of the swap fee. 10,000 = 100%.
uint256 internal constant FEE_SCALE = 10000;
////////////////////////////////////////////////////
/// Immutables
////////////////////////////////////////////////////
/// @notice The minimum amount of active market shares that can be redeemed during allocation.
uint256 public immutable minSharesToRedeem;
/// @notice Minimum excess liquidity delta before allocation will move funds to an active market.
/// This should be close to zero.
/// @dev Prevents allocation from repeatedly bouncing around a near-zero target delta.
int256 public immutable allocateThreshold;
/// @notice Asset used for LP deposits, LP redeem claims, and base-asset quote pricing.
address public immutable liquidityAsset;
/// @notice Delay before an LP redeem request can be claimed in seconds. eg 600 is 10 minutes.
uint256 public immutable claimDelay;
////////////////////////////////////////////////////
/// Storage
////////////////////////////////////////////////////
/// @dev Legacy single-base storage. Keep this prefix unchanged for existing proxy upgrades.
/// These fields are retained for storage/ABI compatibility and are not the source of truth for
/// multi-base swap pricing.
uint256 internal _deprecatedTraderate0;
uint256 internal _deprecatedTraderate1;
uint256 internal _deprecatedCrossPrice;
/// @dev Legacy asset-denominated queue counters retained for storage layout compatibility.
uint128 internal _deprecatedWithdrawsQueued;
uint128 internal _deprecatedWithdrawsClaimed;
/// @notice Index of the next LP withdrawal request.
uint256 public nextWithdrawalIndex;
/// @notice LP withdrawal request for liquidity assets.
struct WithdrawalRequest {
address withdrawer;
bool claimed;
/// @notice Timestamp after which the request can be claimed.
uint40 claimTimestamp;
/// @notice Liquidity assets requested at request time.
uint128 assets;
/// @notice Cumulative queued LP shares including this request.
uint128 queued;
/// @notice LP shares escrowed when this request was made.
uint128 shares;
}
/// @notice Mapping of LP withdrawal request ids to request data.
mapping(uint256 requestId => WithdrawalRequest) public withdrawalRequests;
/// @notice Swap fee share collected on discounted base-asset buy swaps, in basis points.
/// 10,000 = 100% fee
/// 500 = 5% fee
uint16 public fee;
/// @dev Deprecated storage retained for layout compatibility.
int128 internal _deprecatedLastAvailableAssets;
/// @notice Account or contract that can collect accrued swap fees.
address public feeCollector;
/// @notice Optional CapManager contract used to enforce LP and total asset caps.
address public capManager;
/// @notice Active ERC-4626 lending market used for excess liquidity.
address public activeMarket;
/// @notice Lending markets that can be used by the ARM.
mapping(address market => bool supported) public supportedMarkets;
/// @notice Percentage of available liquid assets to keep in the ARM. 100% = 1e18.
uint256 public armBuffer;
/// @notice True when user-facing ARM actions are paused.
bool public paused;
/// @notice Accrued swap fees denominated in the liquidity asset.
uint128 public feesAccrued;
/// @notice Per-base-asset swap, valuation, and adapter configuration.
/// @dev Packed into three storage slots. `adapter != address(0)` is the supported-asset flag.
struct BaseAssetConfig {
/// @notice Price the ARM pays in liquidity-asset terms when buying this base asset from traders.
uint128 buyPrice;
/// @notice Price the ARM charges in liquidity-asset terms when selling this base asset to traders.
uint128 sellPrice;
/// @notice Remaining liquidity asset the ARM can pay out at the current buy price.
uint128 buyLiquidityRemaining;
/// @notice Remaining base asset the ARM can sell at the current sell price.
uint128 sellLiquidityRemaining;
/// @notice Valuation price used by totalAssets(), scaled to 36 decimals.
uint128 crossPrice;
/// @notice Liquidity-denominated value expected from adapter redemption queues.
uint120 pendingRedeemAssets;
/// @notice If true, conversions bypass the adapter and use 1:1 amounts.
bool peggedToLiquidityAsset;
/// @notice Adapter that owns protocol-specific redemption logic for this base asset.
address adapter;
}
/// @notice Supported base assets for totalAssets() iteration.
address[] internal baseAssets;
/// @notice Base asset configuration. A zero adapter means unsupported.
mapping(address asset => BaseAssetConfig) public baseAssetConfigs;
/// @notice Cumulative LP shares queued for redemption, used by the FIFO gate.
uint128 public withdrawsQueuedShares;
/// @notice Cumulative LP shares claimed and burned.
uint128 public withdrawsClaimedShares;
/// @notice Maximum liquidity assets reserved for outstanding LP withdrawal requests.
uint256 public reservedWithdrawLiquidity;
uint256[33] private _gap;
////////////////////////////////////////////////////
/// Errors
////////////////////////////////////////////////////
error UnsupportedAsset(); // 0x24a01144
error InvalidAsset(); // 0xc891add2
error InvalidAdapter(); // 0xfbf66df1
error AssetAlreadySupported(); // 0xb1093e5b
error InvalidAssetDecimals(); // 0xe2364765
error InvalidAdapterAsset(); // 0x030f0830
error InvalidBuyPrice(); // 0x36c64b27
error SellPriceTooLow(); // 0x2394065c
error CrossPriceTooLow(); // 0xea59e662
error CrossPriceTooHigh(); // 0x682101d7
error TooManyBaseAssets(); // 0x94049173
error FeeTooHigh(); // 0xcd4e6167
error InvalidFeeCollector(); // 0xbb0bac99
error InvalidMarket(); // 0x9db8d5b1
error InvalidMarketAsset(); // 0xb9ced245
error MarketAlreadySupported(); // 0xf8d9e05f
error MarketNotSupported(); // 0x7f972548
error MarketActive(); // 0xaeb31949
error InvalidARMBuffer(); // 0x06f77af9
error ContractPaused(); // 0xab35696f
error Insolvent(); // 0xfc220038
error ZeroShares(); // 0x9811e0c7
error ClaimDelayNotMet(); // 0x4a1eec28
error QueuePendingLiquidity(); // 0xa5e8d7ac
error NotRequesterOrOperator(); // 0x40e6afe4
error AlreadyClaimed(); // 0x646cf558
////////////////////////////////////////////////////
/// Events
////////////////////////////////////////////////////
event BaseAssetAdded(
address indexed asset,
address indexed adapter,
uint256 buyPrice,
uint256 sellPrice,
uint256 crossPrice,
bool peggedToLiquidityAsset
);
event TraderateChanged(
address indexed asset,
uint256 buyPrice,
uint256 sellPrice,
uint256 buyLiquidityRemaining,
uint256 sellLiquidityRemaining
);
event CrossPriceUpdated(address indexed asset, uint256 crossPrice);
event Deposit(address indexed owner, uint256 assets, uint256 shares);
event RedeemRequested(
address indexed withdrawer, uint256 indexed requestId, uint256 assets, uint256 queued, uint256 claimTimestamp
);
event RedeemClaimed(address indexed withdrawer, uint256 indexed requestId, uint256 assets);
event FeeCollected(address indexed feeCollector, uint256 fee);
event FeeUpdated(uint256 fee);
event FeeCollectorUpdated(address indexed newFeeCollector);
event CapManagerUpdated(address indexed capManager);
event ActiveMarketUpdated(address indexed market);
event MarketAdded(address indexed market);
event MarketRemoved(address indexed market);
event ARMBufferUpdated(uint256 armBuffer);
event Allocated(address indexed market, int256 targetLiquidityDelta, int256 actualLiquidityDelta);
event Paused(address indexed account);
event Unpaused(address indexed account);
////////////////////////////////////////////////////
/// Modifiers
////////////////////////////////////////////////////
modifier whenNotPaused() {
if (paused) revert ContractPaused();
_;
}
////////////////////////////////////////////////////
/// Constructor
////////////////////////////////////////////////////
/// @param _liquidityAsset Asset used for LP deposits/redeems and base-asset quote pricing.
/// @param _claimDelay Delay in seconds before an LP redeem request can be claimed.
/// eg 600 is 10 minutes.
/// @param _minSharesToRedeem Minimum active market shares to redeem when pulling liquidity.
/// @param _allocateThreshold Minimum excess liquidity delta before allocation deposits into a market.
/// eg 1e18 is 1 liquidity asset.
constructor(address _liquidityAsset, uint256 _claimDelay, uint256 _minSharesToRedeem, int256 _allocateThreshold) {
require(IERC20(_liquidityAsset).decimals() == 18);
require(_allocateThreshold >= 0, "invalid allocate threshold");
liquidityAsset = _liquidityAsset;
claimDelay = _claimDelay;
minSharesToRedeem = _minSharesToRedeem;
allocateThreshold = _allocateThreshold;
// Revoke owner for implementation contract at deployment
_setOwner(address(0));
}
////////////////////////////////////////////////////
/// Initializer
////////////////////////////////////////////////////
/// @notice Initialize storage for the proxy.
/// @dev The initializer caller must approve this ARM proxy to transfer `MIN_TOTAL_SUPPLY` liquidity assets.
/// @param _operator Account allowed to run operator-only actions.
/// @param _name LP token name.
/// @param _symbol LP token symbol.
/// @param _fee Fee on discounted base-asset buy swaps measured in basis points.
/// 10,000 = 100% fee
/// 500 = 5% fee
/// @param _feeCollector Account or contract that receives accrued swap fees.
/// @param _capManager Optional CapManager contract. Use address(0) to disable caps.
function _initARM(
address _operator,
string calldata _name,
string calldata _symbol,
uint256 _fee,
address _feeCollector,
address _capManager
) internal {
_initOwnableOperable(_operator);
__ERC20_init(_name, _symbol);
__ReentrancyGuard_init();
// Transfer a small bit of liquidity from the initializer to this contract.
IERC20(liquidityAsset).transferFrom(msg.sender, address(this), MIN_TOTAL_SUPPLY);
// Mint a small amount of shares to a dead account so total supply can never be zero.
// This avoids donation attacks when there are no assets in the ARM contract.
_mint(DEAD_ACCOUNT, MIN_TOTAL_SUPPLY);
_setFee(_fee);
_setFeeCollector(_feeCollector);
capManager = _capManager;
emit CapManagerUpdated(_capManager);
}
////////////////////////////////////////////////////
/// Swap Functions
////////////////////////////////////////////////////
/// @notice Swap an exact amount of input tokens for as many output tokens as possible.
/// @param inToken Token transferred from the caller.
/// @param outToken Token transferred to `to`.
/// @param amountIn Exact amount of `inToken` to swap.
/// @param amountOutMin Minimum acceptable `outToken` amount.
/// @param to Recipient of `outToken`.
/// @return amounts Two-element array containing input and output amounts.
function swapExactTokensForTokens(
IERC20 inToken,
IERC20 outToken,
uint256 amountIn,
uint256 amountOutMin,
address to
) external virtual whenNotPaused nonReentrant returns (uint256[] memory amounts) {
uint256 amountOut = _swapExactTokensForTokens(inToken, outToken, amountIn, to);
require(amountOut >= amountOutMin, "ARM: Insufficient output amount");
amounts = new uint256[](2);
amounts[0] = amountIn;
amounts[1] = amountOut;
}
/// @notice Uniswap V2 Router compatible exact-input swap.
/// @param amountIn Exact amount of path[0] to swap.
/// @param amountOutMin Minimum acceptable path[1] amount.
/// @param path Two-token path of input and output token addresses.
/// @param to Recipient of output tokens.
/// @param deadline Unix timestamp after which the swap reverts.
/// @return amounts Two-element array containing input and output amounts.
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual whenNotPaused nonReentrant returns (uint256[] memory amounts) {
require(path.length == 2, "ARM: Invalid path length");
_inDeadline(deadline);
uint256 amountOut = _swapExactTokensForTokens(IERC20(path[0]), IERC20(path[1]), amountIn, to);
require(amountOut >= amountOutMin, "ARM: Insufficient output amount");
amounts = new uint256[](2);
amounts[0] = amountIn;
amounts[1] = amountOut;
}
/// @notice Receive an exact amount of output tokens for as few input tokens as possible.
/// @param inToken Token transferred from the caller.
/// @param outToken Token transferred to `to`.
/// @param amountOut Exact amount of `outToken` to receive.
/// @param amountInMax Maximum acceptable `inToken` amount.
/// @param to Recipient of `outToken`.
/// @return amounts Two-element array containing input and output amounts.
function swapTokensForExactTokens(
IERC20 inToken,
IERC20 outToken,
uint256 amountOut,
uint256 amountInMax,
address to
) external virtual whenNotPaused nonReentrant returns (uint256[] memory amounts) {
uint256 amountIn = _swapTokensForExactTokens(inToken, outToken, amountOut, to);
require(amountIn <= amountInMax, "ARM: Excess input amount");
amounts = new uint256[](2);
amounts[0] = amountIn;
amounts[1] = amountOut;
}
/// @notice Uniswap V2 Router compatible exact-output swap.
/// @param amountOut Exact amount of path[1] to receive.
/// @param amountInMax Maximum acceptable path[0] amount.
/// @param path Two-token path of input and output token addresses.
/// @param to Recipient of output tokens.
/// @param deadline Unix timestamp after which the swap reverts.
/// @return amounts Two-element array containing input and output amounts.
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual whenNotPaused nonReentrant returns (uint256[] memory amounts) {
require(path.length == 2, "ARM: Invalid path length");
_inDeadline(deadline);
uint256 amountIn = _swapTokensForExactTokens(IERC20(path[0]), IERC20(path[1]), amountOut, to);
require(amountIn <= amountInMax, "ARM: Excess input amount");
amounts = new uint256[](2);
amounts[0] = amountIn;
amounts[1] = amountOut;
}
/// @param deadline Unix timestamp that must not be in the past.
function _inDeadline(uint256 deadline) internal view {
require(deadline >= block.timestamp, "ARM: Deadline expired");
}
////////////////////////////////////////////////////
/// Swap Internals
////////////////////////////////////////////////////
/// @dev Swap exact input between the liquidity asset and one supported base asset.
/// @param inToken Token transferred from the caller.
/// @param outToken Token transferred to `to`.
/// @param amountIn Exact amount of `inToken` to swap.
/// @param to Recipient of `outToken`.
/// @return amountOut Amount of `outToken` transferred to `to`.
function _swapExactTokensForTokens(IERC20 inToken, IERC20 outToken, uint256 amountIn, address to)
internal
returns (uint256 amountOut)
{
(BaseAssetConfig storage config, bool isBuySide) = _getSwapConfig(address(inToken), address(outToken));
if (!isBuySide) {
// Trader sells liquidity asset and buys the base asset.
// The ARM buys the liquidity asset and sells the base asset.
// ARM prices the base sale at sellPrice.
uint256 convertedAmountIn = _convertToShares(config, amountIn);
// sellPrice is liquidity assets per base asset, so divide liquidity input by sellPrice
// to get the base output owed to the trader.
amountOut = convertedAmountIn * PRICE_SCALE / config.sellPrice;
} else {
// Trader sells base asset and buys the liquidity asset.
// The ARM buys the base asset and sells the liquidity asset.
// ARM prices the base purchase at buyPrice.
uint256 convertedAmountIn = _convertToAssets(config, amountIn);
// buyPrice is liquidity assets per base asset. Since convertedAmountIn is the
// base input expressed in liquidity terms, multiply by buyPrice to get liquidity output.
amountOut = convertedAmountIn * config.buyPrice / PRICE_SCALE;
}
_validateAndConsumeSwapLiquidity(config, isBuySide, outToken, amountOut);
// Transfer the input tokens from the caller to this ARM contract
inToken.transferFrom(msg.sender, address(this), amountIn);
// Transfer the output tokens to the recipient
outToken.transfer(to, amountOut);
}
/// @dev Swap for exact output between the liquidity asset and one supported base asset.
/// @param inToken Token transferred from the caller.
/// @param outToken Token transferred to `to`.
/// @param amountOut Exact amount of `outToken` to receive.
/// @param to Recipient of `outToken`.
/// @return amountIn Amount of `inToken` transferred from the caller.
function _swapTokensForExactTokens(IERC20 inToken, IERC20 outToken, uint256 amountOut, address to)
internal
returns (uint256 amountIn)
{
(BaseAssetConfig storage config, bool isBuySide) = _getSwapConfig(address(inToken), address(outToken));
if (!isBuySide) {
// Trader sells liquidity asset and buys the base asset.
// The ARM buys the liquidity asset and sells the base asset.
// ARM prices the base sale at sellPrice.
uint256 convertedAmountOut = _convertToAssets(config, amountOut);
// amountOut is converted to liquidity terms first, then multiplied by sellPrice
// to solve for the required liquidity input.
// + 3 wei buffer for stETH rounding on larger transfers (observed up to 2 wei; 3 is for safety).
amountIn = convertedAmountOut * config.sellPrice / PRICE_SCALE + 3;
} else {
// Trader sells base asset and buys the liquidity asset.
// The ARM buys the base asset and sells the liquidity asset.
// ARM prices the base purchase at buyPrice.
uint256 convertedAmountOut = _convertToShares(config, amountOut);
// buyPrice is liquidity assets per base asset, but amountIn is base assets.
// Divide the exact liquidity output by buyPrice to solve for the required base input.
amountIn = convertedAmountOut * PRICE_SCALE / config.buyPrice + 3;
}
_validateAndConsumeSwapLiquidity(config, isBuySide, outToken, amountOut);
// Transfer the input tokens from the caller to this ARM contract
inToken.transferFrom(msg.sender, address(this), amountIn);
// Transfer the output tokens to the recipient
outToken.transfer(to, amountOut);
}
/// @dev Resolve the supported base asset config from a 2-token swap pair.
/// @param inToken Swap input token address.
/// @param outToken Swap output token address.
/// @return config Supported base asset config involved in the swap.
/// @return isBuySide True when the ARM buys base asset and pays out liquidity asset.
function _getSwapConfig(address inToken, address outToken)
internal
view
returns (BaseAssetConfig storage config, bool isBuySide)
{
if (outToken == liquidityAsset) {
config = baseAssetConfigs[inToken];
if (config.adapter != address(0)) return (config, true);
} else if (inToken == liquidityAsset) {
config = baseAssetConfigs[outToken];
if (config.adapter != address(0)) return (config, false);
}
revert("ARM: Invalid swap assets");
}
/// @dev Ensure enough unreserved liquidity exists for a swap, withdrawing from the active market if needed.
/// @param amount Liquidity asset amount needed by the swap.
function _ensureLiquidityAvailableForSwap(uint256 amount) internal {
uint256 liquidityBalance = IERC20(liquidityAsset).balanceOf(address(this));
uint256 requiredLiquidity = amount + reservedWithdrawLiquidity;
if (requiredLiquidity <= liquidityBalance) return;
address activeMarketMem = activeMarket;
require(activeMarketMem != address(0), "ARM: Insufficient liquidity");
uint256 shortfall = requiredLiquidity - liquidityBalance;
try IERC4626(activeMarketMem).withdraw(shortfall, address(this), address(this)) {}
catch {
revert("ARM: Insufficient liquidity");
}
}
/// @dev Validate swap reserves and consume the per-base liquidity limit.
/// @param isBuySide True when the ARM buys base asset and pays out liquidity asset.
/// @param outToken Swap output token address.
/// @param amountOut Swap output token amount.
function _validateAndConsumeSwapLiquidity(
BaseAssetConfig storage config,
bool isBuySide,
IERC20 outToken,
uint256 amountOut
) private {
uint256 remaining;
if (isBuySide) {
_accrueSwapFee(config.buyPrice, config.crossPrice, amountOut);
remaining = config.buyLiquidityRemaining;
require(amountOut <= remaining, "ARM: Insufficient liquidity");
unchecked {
config.buyLiquidityRemaining = uint128(remaining - amountOut);
}
_ensureLiquidityAvailableForSwap(amountOut);
} else {
require(amountOut <= outToken.balanceOf(address(this)), "ARM: Insufficient liquidity");
remaining = config.sellLiquidityRemaining;
require(amountOut <= remaining, "ARM: Insufficient liquidity");
unchecked {
config.sellLiquidityRemaining = uint128(remaining - amountOut);
}
}
}
/// @dev Convert base shares to liquidity assets, bypassing the adapter for pegged assets.
/// @param config Base asset config that controls conversion behavior.
/// @param shares Base asset share amount.
/// @return assets Liquidity-denominated asset amount.
function _convertToAssets(BaseAssetConfig memory config, uint256 shares) internal view returns (uint256 assets) {
if (config.peggedToLiquidityAsset) return shares;
return IAssetAdapter(config.adapter).convertToAssets(shares);
}
/// @dev Convert liquidity assets to base shares, bypassing the adapter for pegged assets.
/// @param config Base asset config that controls conversion behavior.
/// @param assets Liquidity-denominated asset amount.
/// @return shares Base asset share amount.
function _convertToShares(BaseAssetConfig memory config, uint256 assets) internal view returns (uint256 shares) {
if (config.peggedToLiquidityAsset) return assets;
return IAssetAdapter(config.adapter).convertToShares(assets);
}
/// @dev Accrue fees on discounted buy-side swaps using the recognized NAV gain.
/// @param buyPrice Price the ARM paid for the base asset.
/// @param crossPrice Price used to value the base asset in totalAssets().
/// @param amountOut Liquidity asset amount paid out by the ARM.
function _accrueSwapFee(uint256 buyPrice, uint256 crossPrice, uint256 amountOut) internal {
uint256 feeMultiplier = (crossPrice - buyPrice) * uint256(fee) * PRICE_SCALE / (buyPrice * FEE_SCALE);
feesAccrued = SafeCast.toUint128(feesAccrued + amountOut * feeMultiplier / PRICE_SCALE);
}
////////////////////////////////////////////////////
/// Base Asset Admin
////////////////////////////////////////////////////
/// @notice Register a supported base asset and its redemption adapter.
/// @param newBaseAsset Base asset to support.
/// @param adapter Asset adapter for conversions and protocol redemption requests.
/// @param buyPrice Price the ARM pays when buying this base asset from traders.
/// eg 0.998e36 is 0.998 liquidity asset per base asset.
/// @param sellPrice Price the ARM charges when selling this base asset to traders.
/// eg 1e36 is 1 liquidity asset per base asset.
/// @param buyAmount Liquidity-asset amount the ARM can pay out at the buy price.
/// eg 100e18 allows the ARM to pay out 100 liquidity assets.
/// @param sellAmount Base-asset amount the ARM can sell at the sell price.
/// eg 100e18 allows the ARM to sell 100 base assets.
/// @param newCrossPrice totalAssets() valuation price for this base asset.
/// eg 1e36 values the base asset at 1 liquidity asset.
/// @param peggedToLiquidityAsset True for 1:1 assets that should skip adapter conversion calls.
function addBaseAsset(
address newBaseAsset,
address adapter,
uint256 buyPrice,
uint256 sellPrice,
uint256 buyAmount,
uint256 sellAmount,
uint256 newCrossPrice,
bool peggedToLiquidityAsset
) external onlyOwner {
if (newBaseAsset == address(0)) revert InvalidAsset();
if (adapter == address(0)) revert InvalidAdapter();
if (baseAssetConfigs[newBaseAsset].adapter != address(0)) revert AssetAlreadySupported();
if (IERC20(newBaseAsset).decimals() != 18) revert InvalidAssetDecimals();
if (IAssetAdapter(adapter).asset() != liquidityAsset) revert InvalidAdapterAsset();
if (newCrossPrice < PRICE_SCALE - MAX_CROSS_PRICE_DEVIATION) revert CrossPriceTooLow();
if (newCrossPrice > PRICE_SCALE) revert CrossPriceTooHigh();
_validatePrices(buyPrice, sellPrice, newCrossPrice);
baseAssets.push(newBaseAsset);
// Allow the adapter to pull base assets when requesting protocol redemptions.
IERC20(newBaseAsset).approve(adapter, type(uint256).max);
baseAssetConfigs[newBaseAsset] = BaseAssetConfig({
buyPrice: SafeCast.toUint128(buyPrice),
sellPrice: SafeCast.toUint128(sellPrice),
buyLiquidityRemaining: SafeCast.toUint128(buyAmount),
sellLiquidityRemaining: SafeCast.toUint128(sellAmount),
crossPrice: SafeCast.toUint128(newCrossPrice),
pendingRedeemAssets: 0,
peggedToLiquidityAsset: peggedToLiquidityAsset,
adapter: adapter
});
emit BaseAssetAdded(newBaseAsset, adapter, buyPrice, sellPrice, newCrossPrice, peggedToLiquidityAsset);
}
/// @notice Set buy/sell prices and per-price liquidity limits for a supported base asset.
/// @param priceBaseAsset Base asset whose prices are being updated.
/// @param buyPrice Price the ARM pays when buying this base asset from traders.
/// eg 0.998e36 is 0.998 liquidity asset per base asset.
/// @param sellPrice Price the ARM charges when selling this base asset to traders.
/// eg 1e36 is 1 liquidity asset per base asset.
/// @param buyAmount Liquidity-asset amount the ARM can pay out at the buy price.
/// eg 100e18 allows the ARM to pay out 100 liquidity assets.
/// @param sellAmount Base-asset amount the ARM can sell at the sell price.
/// eg 100e18 allows the ARM to sell 100 base assets.
function setPrices(
address priceBaseAsset,
uint256 buyPrice,
uint256 sellPrice,
uint256 buyAmount,
uint256 sellAmount
) external onlyOperatorOrOwner {
BaseAssetConfig storage config = baseAssetConfigs[priceBaseAsset];
if (config.adapter == address(0)) revert UnsupportedAsset();
_validatePrices(buyPrice, sellPrice, config.crossPrice);
config.buyPrice = SafeCast.toUint128(buyPrice);
config.sellPrice = SafeCast.toUint128(sellPrice);
config.buyLiquidityRemaining = SafeCast.toUint128(buyAmount);
config.sellLiquidityRemaining = SafeCast.toUint128(sellAmount);
emit TraderateChanged(priceBaseAsset, buyPrice, sellPrice, buyAmount, sellAmount);
}
function _validatePrices(uint256 buyPrice, uint256 sellPrice, uint256 crossPrice) internal pure {
if (sellPrice < crossPrice) revert SellPriceTooLow();
if (buyPrice < MAX_CROSS_PRICE_DEVIATION || buyPrice >= crossPrice) revert InvalidBuyPrice();
}
/// @notice Set the valuation price that buy and sell prices may not cross for a base asset.
/// @dev When lowering cross price, the ARM must not have meaningful exposure to that base asset
/// either on-hand or in the adapter withdrawal queue.
/// @param priceBaseAsset Base asset whose cross price is being updated.
/// @param newCrossPrice New valuation price scaled to 36 decimals.
/// eg 1e36 values the base asset at 1 liquidity asset.
function setCrossPrice(address priceBaseAsset, uint256 newCrossPrice) external onlyOwner {
BaseAssetConfig storage config = baseAssetConfigs[priceBaseAsset];
if (config.adapter == address(0)) revert UnsupportedAsset();
if (newCrossPrice < PRICE_SCALE - MAX_CROSS_PRICE_DEVIATION) revert CrossPriceTooLow();
if (newCrossPrice > PRICE_SCALE) revert CrossPriceTooHigh();
if (config.sellPrice < newCrossPrice) revert SellPriceTooLow();
if (config.buyPrice >= newCrossPrice) revert InvalidBuyPrice();
if (newCrossPrice < config.crossPrice) {
uint256 baseAssetExposure =
_convertToAssets(config, IERC20(priceBaseAsset).balanceOf(address(this))) + config.pendingRedeemAssets;
if (baseAssetExposure >= MIN_TOTAL_SUPPLY) revert TooManyBaseAssets();
}
config.crossPrice = SafeCast.toUint128(newCrossPrice);
emit CrossPriceUpdated(priceBaseAsset, newCrossPrice);
}
////////////////////////////////////////////////////
/// Adapter Redeems
////////////////////////////////////////////////////
/// @notice Request protocol redemption of a base asset through its adapter.
/// @dev Increases `pendingRedeemAssets` by the liquidity-denominated amount expected from the adapter.
/// @param redeemBaseAsset Base asset to redeem through its adapter.
/// @param shares Base asset shares to submit for protocol redemption.
/// @return sharesRequested Base asset shares accepted by the adapter.
/// @return assetsExpected Liquidity-denominated assets expected from the redemption.
function requestBaseAssetRedeem(address redeemBaseAsset, uint256 shares)
external
onlyOperatorOrOwner
returns (uint256 sharesRequested, uint256 assetsExpected)
{
BaseAssetConfig storage config = baseAssetConfigs[redeemBaseAsset];
if (config.adapter == address(0)) revert UnsupportedAsset();
(sharesRequested, assetsExpected) = IAssetAdapter(config.adapter).requestRedeem(shares);
// Track the liquidity-denominated value expected back from the adapter queue.
config.pendingRedeemAssets = SafeCast.toUint120(uint256(config.pendingRedeemAssets) + assetsExpected);
}
/// @notice Claim protocol redemptions through a base asset adapter.
/// @dev Decreases `pendingRedeemAssets` by expected assets. If a protocol returns less than expected,
/// the shortfall naturally reduces totalAssets() once the pending amount is removed.
/// @param redeemBaseAsset Base asset whose adapter redemption should be claimed.
/// @param shares Base asset shares to claim from the adapter's FIFO queue.
/// @return sharesClaimed Base asset shares claimed by the adapter.
/// @return assetsExpected Liquidity-denominated assets expected from the claimed redemptions.
/// @return assetsReceived Liquidity assets actually received by the ARM.
function claimBaseAssetRedeem(address redeemBaseAsset, uint256 shares)
external
onlyOperatorOrOwner
returns (uint256 sharesClaimed, uint256 assetsExpected, uint256 assetsReceived)
{
BaseAssetConfig storage config = baseAssetConfigs[redeemBaseAsset];
if (config.adapter == address(0)) revert UnsupportedAsset();
(sharesClaimed, assetsExpected, assetsReceived) = IAssetAdapter(config.adapter).redeem(shares);
// Remove expected queue value. Any received shortfall remains reflected in totalAssets().
config.pendingRedeemAssets = SafeCast.toUint120(uint256(config.pendingRedeemAssets) - assetsExpected);
}
////////////////////////////////////////////////////
/// LP Deposits
////////////////////////////////////////////////////
/// @notice Preview LP shares minted for a liquidity-asset deposit.
/// @param assets Liquidity assets to deposit.
/// @return shares LP shares that would be minted.
function previewDeposit(uint256 assets) external view returns (uint256 shares) {
shares = convertToShares(assets);
}
/// @notice Deposit liquidity assets and mint LP shares to the caller.
/// The caller needs to have approved the ARM contract to transfer the assets.
/// @param assets Liquidity assets to deposit.
/// @return shares LP shares minted.
function deposit(uint256 assets) external whenNotPaused nonReentrant returns (uint256 shares) {
shares = _deposit(assets, msg.sender);
}
/// @notice Deposit liquidity assets and mint LP shares to `receiver`.
/// @param assets Liquidity assets to deposit.
/// @param receiver Account that receives minted LP shares.
/// @return shares LP shares minted.
function deposit(uint256 assets, address receiver) external whenNotPaused nonReentrant returns (uint256 shares) {
shares = _deposit(assets, receiver);
}
/// @dev Internal liquidity deposit implementation.
/// @param assets Liquidity assets to deposit.
/// @param receiver Account that receives minted LP shares.
/// @return shares LP shares minted.
function _deposit(uint256 assets, address receiver) internal returns (uint256 shares) {
if (totalAssets() <= MIN_TOTAL_SUPPLY && reservedWithdrawLiquidity != 0) revert Insolvent();
shares = convertToShares(assets);
// Transfer liquidity from the depositor before minting LP shares.
IERC20(liquidityAsset).transferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
// Enforce LP caps after the deposit has changed the receiver's share balance.
if (capManager != address(0)) ICapManager(capManager).postDepositHook(receiver, assets);
emit Deposit(receiver, assets, shares);
}
////////////////////////////////////////////////////
/// LP Redeems
////////////////////////////////////////////////////
/// @notice Preview liquidity assets redeemable for LP shares.
/// @param shares LP shares to redeem.
/// @return assets Liquidity assets that would be redeemable.
function previewRedeem(uint256 shares) external view returns (uint256 assets) {
assets = convertToAssets(shares);
}
/// @notice Request to redeem LP shares for liquidity assets after the claim delay.
/// @param shares LP shares to burn.
/// @return requestId The LP withdrawal request id.
/// @return assets The maximum liquidity assets claimable by the redeemer.
function requestRedeem(uint256 shares)
external
whenNotPaused
nonReentrant
returns (uint256 requestId, uint256 assets)
{
if (shares == 0) revert ZeroShares();
assets = convertToAssets(shares);
requestId = nextWithdrawalIndex;
// Store the next withdrawal request id.
nextWithdrawalIndex = requestId + 1;
// Cumulative shares queued including this request, used for the FIFO gate at claim. The
// request-time asset cap is tracked separately in `assets` and is not the claimability unit.
uint128 queued = SafeCast.toUint128(withdrawsQueuedShares + shares);
withdrawsQueuedShares = queued;
// Reserve the request-time maximum liquidity payout.
reservedWithdrawLiquidity += assets;
uint40 claimTimestamp = uint40(block.timestamp + claimDelay);
withdrawalRequests[requestId] = WithdrawalRequest({
withdrawer: msg.sender,
claimed: false,
claimTimestamp: claimTimestamp,
assets: SafeCast.toUint128(assets),
queued: queued,
shares: SafeCast.toUint128(shares)
});
// Escrow the redeemer's shares so they stay in totalSupply() and share losses/gains pro-rata.
_transfer(msg.sender, address(this), shares);
emit RedeemRequested(msg.sender, requestId, assets, queued, claimTimestamp);
}
/// @notice Claim liquidity assets from a matured LP withdrawal request.
/// @dev New requests use a share-denominated FIFO gate: `request.queued <= claimable()`.
/// If assets per share decreased after request time, the claim uses the lower claim-time value.
/// If non-liquid NAV increases without a matching increase in claimable liquidity, `claimable()` can
/// decrease in share terms even when the request-time asset cap is fully backed by liquid assets.
/// For example, a fully funded 90-share request can become pending if 90 liquid assets are valued
/// against 100.1 total assets and 100 total shares: `90 * 100 / 100.1 = 89.91` claimable shares.
/// @param requestId LP withdrawal request id to claim.
/// @return assets Liquidity assets transferred to the requester.
function claimRedeem(uint256 requestId) external whenNotPaused nonReentrant returns (uint256 assets) {
WithdrawalRequest memory request = withdrawalRequests[requestId];
if (request.claimTimestamp > block.timestamp) revert ClaimDelayNotMet();
if (request.queued > claimable()) revert QueuePendingLiquidity();
if (request.withdrawer != msg.sender && msg.sender != operator) revert NotRequesterOrOperator();
if (request.claimed) revert AlreadyClaimed();
// In the scenario where the ARM has made a loss after the redeem request, the asset value of
// the redeemed shares at the time of the claim is used.
// This can happen if there was a significant slashing event on the base asset, eg stETH,
// after the redeem request was made.
uint256 assetsAtClaim = convertToAssets(request.shares);
// Use the minimum of the asset value of the redeemed shares at request or claim.
assets = request.assets < assetsAtClaim ? request.assets : assetsAtClaim;
// Release the full request-time reservation, even when a loss-adjusted payout is lower.
reservedWithdrawLiquidity -= request.assets;
// Cumulative claimed amount in shares, used by the FIFO gate above.
withdrawsClaimedShares += request.shares;
// Burn the escrowed shares after `assets` was computed so conversion uses the pre-claim supply.
_burn(address(this), request.shares);
// Store the request as claimed.
withdrawalRequests[requestId].claimed = true;
_pullLiquidityForRedeem(assets);
// Transfer the liquidity asset to the withdrawer.
IERC20(liquidityAsset).transfer(request.withdrawer, assets);
emit RedeemClaimed(request.withdrawer, requestId, assets);
}
/// @dev Pull liquidity from the active market if the ARM does not hold enough to pay a redeem claim.
function _pullLiquidityForRedeem(uint256 assets) private {
// If there is not enough liquidity assets in the ARM, get from the active market if one is configured.
// Read the active market address from storage once to save gas.
address activeMarketMem = activeMarket;
if (activeMarketMem != address(0)) {
uint256 liquidityInARM = IERC20(liquidityAsset).balanceOf(address(this));
if (assets > liquidityInARM) {
uint256 liquidityFromMarket = assets - liquidityInARM;
// This should work as we have checked earlier the claimable liquidity which includes the active market.
IERC4626(activeMarketMem).withdraw(liquidityFromMarket, address(this), address(this));
}
}
}
////////////////////////////////////////////////////
/// Accounting
////////////////////////////////////////////////////
/// @notice Cumulative share queue frontier currently backed by claimable liquidity.
/// @dev Converts on-hand liquidity plus active-market `maxWithdraw` into shares at the current
/// `totalAssets()` valuation. Because this is share-denominated, non-liquid NAV gains from supported
/// base-asset donations, rebases, discounted buys, adapter queues, or active-market appreciation can
/// reduce the returned share frontier unless claimable liquidity increases proportionally. This can
/// make a request remain pending even when its request-time asset cap is fully backed by liquid assets.
/// @return claimableShares Requests with `queued <= claimableShares` can be claimed once their delay has elapsed.
function claimable() public view returns (uint256 claimableShares) {
uint256 claimableLiquidity = IERC20(liquidityAsset).balanceOf(address(this));
// If there is an active lending market, add to the claimable amount.
address activeMarketMem = activeMarket;
if (activeMarketMem != address(0)) {
// maxWithdraw is used as during periods of high utilization or temporary pauses,
// maxWithdraw may return less than convertToAssets.
claimableLiquidity += IERC4626(activeMarketMem).maxWithdraw(address(this));
}
claimableShares = withdrawsClaimedShares + convertToShares(claimableLiquidity);
}
/// @notice Get available liquidity and base asset reserves for a supported base asset.
/// @param reserveBaseAsset Supported base asset whose reserve should be returned.
/// @return liquidityAssets Available liquidity assets net of outstanding LP withdrawal claims.
/// @return baseAssetReserve Base assets held directly by the ARM.
function getReserves(address reserveBaseAsset)
external
view
returns (uint256 liquidityAssets, uint256 baseAssetReserve)
{
require(baseAssetConfigs[reserveBaseAsset].adapter != address(0), "ARM: unsupported asset");
liquidityAssets = IERC20(liquidityAsset).balanceOf(address(this));
address activeMarketMem = activeMarket;
if (activeMarketMem != address(0)) {
// maxWithdraw is used because reserve liquidity should reflect what can currently be pulled.
liquidityAssets += IERC4626(activeMarketMem).maxWithdraw(address(this));
}
uint256 reservedWithdrawLiquidityMem = reservedWithdrawLiquidity;
liquidityAssets =
reservedWithdrawLiquidityMem > liquidityAssets ? 0 : liquidityAssets - reservedWithdrawLiquidityMem;
baseAssetReserve = IERC20(reserveBaseAsset).balanceOf(address(this));
}
/// @notice Economic value of ARM assets net of accrued swap fees.
/// @return Total liquidity-denominated assets available to LP shares.
function totalAssets() public view virtual returns (uint256) {
uint256 newAvailableAssets = _availableAssets();
uint256 feesAccruedMem = feesAccrued;
// total assets should only go up from the initial deposit amount that is burnt,
// but in case of something unforeseen, return at least MIN_TOTAL_SUPPLY.
// An example scenario that will return MIN_TOTAL_SUPPLY is:
// First LP deposits and then requests a redeem of all their ARM shares.
// While waiting to claim their request, the ARM suffers a loss of assets. eg lending market loss.
// When they claim their request, newAvailableAssets can be zero as the ARM assets can be less than
// the outstanding withdrawal request that was calculated before the loss.
if (feesAccruedMem + MIN_TOTAL_SUPPLY >= newAvailableAssets) return MIN_TOTAL_SUPPLY;
// Remove accrued swap fees from the available assets.
return newAvailableAssets - feesAccruedMem;
}
/// @notice Liquidity asset used for LP deposits and redeems.
/// @dev ERC-4626 compatibility view.
/// @return The liquidity asset address.
function asset() external view virtual returns (address) {
return liquidityAsset;
}
/// @dev Calculate ARM asset value before accrued swap fees are removed.
/// Includes on-hand liquidity, active market value, base balances valued at cross price, and adapter queues.
/// Queued redemption shares stay in totalSupply(), so the share price already reflects outstanding claims.
/// @return availableAssets Liquidity-denominated assets before accrued swap fees.
function _availableAssets() internal view returns (uint256 availableAssets) {
availableAssets = IERC20(liquidityAsset).balanceOf(address(this));
uint256 length = baseAssets.length;
for (uint256 i = 0; i < length; ++i) {
address supportedBaseAsset = baseAssets[i];
BaseAssetConfig memory config = baseAssetConfigs[supportedBaseAsset];
// Base assets in the ARM are converted to liquidity assets and then the cross price is applied.
// The cross price is the discounted price for the redemption time delay. This ensures the ARM's
// assets per share does not decrease if the ARM sells base assets at a discount, because the base
// sell price is greater than or equal to the cross price.
uint256 baseConvertedToLiquid =
_convertToAssets(config, IERC20(supportedBaseAsset).balanceOf(address(this)));
availableAssets += baseConvertedToLiquid * config.crossPrice / PRICE_SCALE;
// Pending adapter redemptions are already tracked in liquidity terms and represent assets
// expected back from protocol withdrawal queues. Value them at the live cross price so moving
// base assets into a withdrawal queue does not create an immediate assets-per-share increase.
availableAssets += uint256(config.pendingRedeemAssets) * config.crossPrice / PRICE_SCALE;
}
address activeMarketMem = activeMarket;
if (activeMarketMem != address(0)) {
// Get all the active lending market shares owned by this ARM contract.
uint256 allShares = IERC4626(activeMarketMem).balanceOf(address(this));
// Value active market shares economically, not by currently withdrawable liquidity.
// Liquidity-aware functions such as claimable() and _allocate() continue to use maxWithdraw,
// maxRedeem, withdraw and redeem when current liquidity matters.
availableAssets += IERC4626(activeMarketMem).convertToAssets(allShares);
}
}
/// @notice Convert liquidity assets to LP shares.
/// @param assets Liquidity assets to convert.
/// @return shares LP shares equivalent to `assets`.
function convertToShares(uint256 assets) public view returns (uint256 shares) {
shares = assets * totalSupply() / totalAssets();
}
/// @notice Convert LP shares to liquidity assets.
/// @param shares LP shares to convert.
/// @return assets Liquidity assets equivalent to `shares`.
function convertToAssets(uint256 shares) public view returns (uint256 assets) {
assets = shares * totalAssets() / totalSupply();
}
////////////////////////////////////////////////////
/// Fees
////////////////////////////////////////////////////
/// @notice Set the fee on discounted base-asset buy swaps.
/// @param _fee Fee measured in basis points. Maximum is 50%.
/// 10,000 = 100% fee
/// 500 = 5% fee
function setFee(uint256 _fee) external onlyOwner {
_setFee(_fee);
}
/// @notice Set the fee collector account.
/// @param _feeCollector Account or contract that receives accrued swap fees.
function setFeeCollector(address _feeCollector) external onlyOwner {
_setFeeCollector(_feeCollector);
}
/// @param _fee Fee measured in basis points. Maximum is 50%.
/// 10,000 = 100% fee
/// 500 = 5% fee
function _setFee(uint256 _fee) internal {
if (_fee > FEE_SCALE / 2) revert FeeTooHigh();
collectFees();
fee = SafeCast.toUint16(_fee);
emit FeeUpdated(_fee);
}
/// @param _feeCollector Account or contract that receives accrued swap fees.
function _setFeeCollector(address _feeCollector) internal {
if (_feeCollector == address(0)) revert InvalidFeeCollector();
feeCollector = _feeCollector;
emit FeeCollectorUpdated(_feeCollector);
}
/// @notice Transfer accrued swap fees to the fee collector.
/// @return fees Liquidity assets transferred to the fee collector.
function collectFees() public nonReentrant returns (uint256 fees) {
fees = feesAccrued;
if (fees == 0) return 0;
// Fees can only be collected from unreserved on-hand liquidity.
require(
fees + reservedWithdrawLiquidity <= IERC20(liquidityAsset).balanceOf(address(this)),
"ARM: Insufficient liquidity"
);
feesAccrued = 0;
IERC20(liquidityAsset).transfer(feeCollector, fees);
emit FeeCollected(feeCollector, fees);
}
////////////////////////////////////////////////////
/// Active Markets
////////////////////////////////////////////////////
/// @notice Add supported ERC-4626 lending markets.
/// @param _markets Market addresses to support.
function addMarkets(address[] calldata _markets) external onlyOwner {
for (uint256 i = 0; i < _markets.length; ++i) {
address market = _markets[i];
if (market == address(0)) revert InvalidMarket();
if (supportedMarkets[market]) revert MarketAlreadySupported();
if (IERC4626(market).asset() != liquidityAsset) revert InvalidMarketAsset();
supportedMarkets[market] = true;
emit MarketAdded(market);
}
}
/// @notice Remove a supported ERC-4626 lending market.
/// @param _market Market address to remove.
function removeMarket(address _market) external onlyOwner {
if (_market == address(0)) revert InvalidMarket();
if (!supportedMarkets[_market]) revert MarketNotSupported();
if (_market == activeMarket) revert MarketActive();
supportedMarkets[_market] = false;
emit MarketRemoved(_market);
}
/// @notice Set the active lending market used for allocation.
/// @dev Redeems all shares from the previous market before switching.
/// @param _market Supported market to activate, or address(0) to disable active allocation.
function setActiveMarket(address _market) external onlyOperatorOrOwner {
if (_market != address(0) && !supportedMarkets[_market]) revert MarketNotSupported();
// Read once from storage to save gas and make it clear this is the previous active market.
address previousActiveMarket = activeMarket;
// Don't revert if the previous active market is the same as the new one.
if (previousActiveMarket == _market) return;
if (previousActiveMarket != address(0)) {
// Redeem all shares from the previous active lending market.
// balanceOf is used instead of maxRedeem to ensure all shares are redeemed.
// maxRedeem can return a smaller amount of shares than balanceOf if the market is highly utilized.
uint256 shares = IERC4626(previousActiveMarket).balanceOf(address(this));
if (shares > 0) {
// This could fail if the market has high utilization. In this case, the Operator needs
// to wait until the utilization drops before setting a new active market.
// The redeem can also fail if the ARM has a dust amount of shares left. eg 100 wei.
// If that happens, the Operator can transfer a tiny amount of active market shares
// to the ARM so the following redeem will not fail.
IERC4626(previousActiveMarket).redeem(shares, address(this), address(this));
}
}
activeMarket = _market;
emit ActiveMarketUpdated(_market);
// Exit if no new active market.
if (_market == address(0)) return;
_allocate();
}
/// @notice Allocate liquidity to or from the active market based on the ARM buffer.
/// @dev The buffer excludes liquidity assets reserved for the ARM's withdrawal queue. That is, more
/// liquidity assets will be withdrawn from the lending market if the ARM's liquidity asset balance
/// does not cover the buffer, which can be zero, and the ARM's outstanding withdrawals.
/// @return targetLiquidityDelta Desired liquidity movement. Positive means deposit, negative means withdraw.
/// @return actualLiquidityDelta Actual liquidity movement. Positive means deposited, negative means withdrawn.
function allocate() external returns (int256 targetLiquidityDelta, int256 actualLiquidityDelta) {
require(activeMarket != address(0), "ARM: no active market");
return _allocate();
}
/// @dev Internal allocation implementation.
/// @return targetLiquidityDelta Desired liquidity movement. Positive means deposit, negative means withdraw.
/// @return actualLiquidityDelta Actual liquidity movement. Positive means deposited, negative means withdrawn.
function _allocate() internal returns (int256 targetLiquidityDelta, int256 actualLiquidityDelta) {
uint256 availableAssets = _availableAssets();
if (availableAssets == 0) return (0, 0);
uint256 targetArmLiquidity = availableAssets * armBuffer / 1e18;
// The current liquidity available to swap is the liquidity asset balance less
// any outstanding withdrawals from the ARM's withdrawal queue.
int256 currentArmLiquidity = SafeCast.toInt256(IERC20(liquidityAsset).balanceOf(address(this)))
- SafeCast.toInt256(reservedWithdrawLiquidity);
targetLiquidityDelta = currentArmLiquidity - SafeCast.toInt256(targetArmLiquidity);
// Load the active lending market address from storage to save gas
address activeMarketMem = activeMarket;
// The allocateThreshold prevents the ARM from constantly depositing and withdrawing if there are rounding issues
if (targetLiquidityDelta > allocateThreshold) {
// We have too much liquidity in the ARM, so deposit some to the active lending market.
uint256 depositAmount = SafeCast.toUint256(targetLiquidityDelta);
IERC20(liquidityAsset).approve(activeMarketMem, depositAmount);
IERC4626(activeMarketMem).deposit(depositAmount, address(this));
actualLiquidityDelta = SafeCast.toInt256(depositAmount);
} else if (targetLiquidityDelta < 0) {
// We have too little liquidity in the ARM, so withdraw some from the active lending market.
uint256 availableMarketAssets = IERC4626(activeMarketMem).maxWithdraw(address(this));
uint256 desiredWithdrawAmount = SafeCast.toUint256(-targetLiquidityDelta);
if (availableMarketAssets < desiredWithdrawAmount) {
// Not enough assets in the market so redeem as much as possible.
// maxRedeem is used instead of balanceOf as we want to redeem as much as possible without failing.
// redeem of the ARM's balance can fail if the lending market is highly utilized or temporarily paused.
// Redeem and not withdrawal is used to avoid leaving a small amount of assets in the market.
uint256 shares = IERC4626(activeMarketMem).maxRedeem(address(this));
if (shares <= minSharesToRedeem) return (targetLiquidityDelta, 0);
// This should not fail according to the ERC-4626 spec as maxRedeem was used earlier
// but it depends on the 4626 implementation of the lending market.
// It may fail if the market is highly utilized and not compliant with 4626.
uint256 redeemedAssets = IERC4626(activeMarketMem).redeem(shares, address(this), address(this));
actualLiquidityDelta = -SafeCast.toInt256(redeemedAssets);
} else {
IERC4626(activeMarketMem).withdraw(desiredWithdrawAmount, address(this), address(this));
actualLiquidityDelta = -SafeCast.toInt256(desiredWithdrawAmount);
}
}
emit Allocated(activeMarketMem, targetLiquidityDelta, actualLiquidityDelta);
}
////////////////////////////////////////////////////
/// Admin Functions
////////////////////////////////////////////////////
/// @notice Pause user-facing ARM actions.
function pause() external onlyOperatorOrOwner {
paused = true;
emit Paused(msg.sender);
}
/// @notice Unpause user-facing ARM actions.
function unpause() external onlyOwner {
paused = false;
emit Unpaused(msg.sender);
}
/// @notice Set the CapManager contract.
/// @param _capManager CapManager contract address, or address(0) to disable caps.
function setCapManager(address _capManager) external onlyOwner {
capManager = _capManager;
emit CapManagerUpdated(_capManager);
}
/// @notice Set the percentage of available liquidity assets to keep on hand. 100% = 1e18.
/// @param _armBuffer Percentage of available assets to keep in the ARM, scaled by 1e18.
/// 1e18 = 100% buffer
/// 0.1e18 = 10% buffer
function setARMBuffer(uint256 _armBuffer) external onlyOperatorOrOwner {
if (_armBuffer > 1e18) revert InvalidARMBuffer();
armBuffer = _armBuffer;
emit ARMBufferUpdated(_armBuffer);
}
/// @notice List of supported base assets iterated by totalAssets().
/// @return The supported base asset addresses.
function getBaseAssets() external view returns (address[] memory) {
return baseAssets;
}
}
src/contracts/Interfaces.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function decimals() external view returns (uint8);
event Transfer(address indexed from, address indexed to, uint256 value);
}
interface ILiquidityProviderARM is IERC20 {
function previewDeposit(uint256 assets) external returns (uint256 shares);
function deposit(uint256 assets) external returns (uint256 shares);
function deposit(uint256 assets, address liquidityProvider) external returns (uint256 shares);
function previewRedeem(uint256 shares) external returns (uint256 assets);
function requestRedeem(uint256 shares) external returns (uint256 requestId, uint256 assets);
function claimRedeem(uint256 requestId) external returns (uint256 assets);
function totalAssets() external returns (uint256 assets);
function convertToShares(uint256 assets) external returns (uint256 shares);
function convertToAssets(uint256 shares) external returns (uint256 assets);
function lastTotalAssets() external returns (uint256 assets);
}
interface ICapManager {
function postDepositHook(address liquidityProvider, uint256 assets) external;
}
/// @notice Adapter interface for assets that require protocol-specific redemption flows.
/// @dev ARM calls adapters when a base asset cannot be redeemed synchronously into the ARM liquidity asset.
interface IAssetAdapter {
/// @notice Returns the liquidity asset received by the ARM after adapter redemptions.
function asset() external view returns (address);
/// @notice Converts adapter share tokens into the expected amount of liquidity assets.
/// @param shares Amount of protocol share tokens.
/// @return assets Expected amount of liquidity assets.
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/// @notice Converts liquidity assets into the expected amount of adapter share tokens.
/// @param assets Amount of liquidity assets.
/// @return shares Expected amount of protocol share tokens.
function convertToShares(uint256 assets) external view returns (uint256 shares);
/// @notice Requests an asynchronous redemption from protocol share tokens into liquidity assets.
/// @dev Implementations pull `shares` from the ARM and record protocol request metadata for later claiming.
/// @param shares Amount of protocol share tokens to redeem.
/// @return sharesRequested Amount of share tokens accepted into the redemption request.
/// @return assetsExpected Expected liquidity assets from the redemption request.
function requestRedeem(uint256 shares) external returns (uint256 sharesRequested, uint256 assetsExpected);
/// @notice Claims previously requested redemptions and sends received liquidity assets to the ARM.
/// @dev Claims must be made in the adapter's pending-request order and may revert if the requested shares are not
/// fully claimable.
/// @param shares Amount of protocol share tokens represented by pending requests to claim.
/// @return sharesClaimed Amount of share tokens represented by claimed requests.
/// @return assetsExpected Expected liquidity assets recorded when the requests were opened.
/// @return assetsReceived Actual liquidity assets received and transferred to the ARM.
function redeem(uint256 shares)
external
returns (uint256 sharesClaimed, uint256 assetsExpected, uint256 assetsReceived);
}
interface LegacyAMM {
function transferToken(address tokenOut, address to, uint256 amount) external;
}
interface IOriginVault {
function mint(address _asset, uint256 _amount, uint256 _minimumOusdAmount) external;
function redeem(uint256 _amount, uint256 _minimumUnitAmount) external;
function requestWithdrawal(uint256 amount) external returns (uint256 requestId, uint256 queued);
function claimWithdrawal(uint256 requestId) external returns (uint256 amount);
function claimWithdrawals(uint256[] memory requestIds)
external
returns (uint256[] memory amounts, uint256 totalAmount);
function addWithdrawalQueueLiquidity() external;
function setMaxSupplyDiff(uint256 _maxSupplyDiff) external;
function governor() external view returns (address);
function dripper() external view returns (address);
function withdrawalQueueMetadata()
external
view
returns (uint128 queued, uint128 claimable, uint128 claimed, uint128 nextWithdrawalIndex);
function withdrawalRequests(uint256 requestId)
external
view
returns (address withdrawer, bool claimed, uint40 timestamp, uint128 amount, uint128 queued);
function withdrawalClaimDelay() external view returns (uint256);
}
interface IGovernance {
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
function state(uint256 proposalId) external view returns (ProposalState);
function proposalSnapshot(uint256 proposalId) external view returns (uint256);
function proposalDeadline(uint256 proposalId) external view returns (uint256);
function proposalEta(uint256 proposalId) external view returns (uint256);
function votingDelay() external view returns (uint256);
function castVote(uint256 proposalId, uint8 support) external returns (uint256 balance);
function queue(uint256 proposalId) external;
function execute(uint256 proposalId) external;
}
interface IWETH is IERC20 {
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function deposit() external payable;
function withdraw(uint256 wad) external;
}
interface ISTETH is IERC20 {
event Submitted(address indexed sender, uint256 amount, address referral);
// function() external payable;
function submit(address _referral) external payable returns (uint256);
}
interface IWstETH is IERC20 {
function getStETHByWstETH(uint256 wstETHAmount) external view returns (uint256);
function getWstETHByStETH(uint256 stETHAmount) external view returns (uint256);
function unwrap(uint256 wstETHAmount) external returns (uint256);
}
interface IStETHWithdrawal {
event WithdrawalRequested(
uint256 indexed requestId,
address indexed requestor,
address indexed owner,
uint256 amountOfStETH,
uint256 amountOfShares
);
event WithdrawalsFinalized(
uint256 indexed from, uint256 indexed to, uint256 amountOfETHLocked, uint256 sharesToBurn, uint256 timestamp
);
event WithdrawalClaimed(
uint256 indexed requestId, address indexed owner, address indexed receiver, uint256 amountOfETH
);
struct WithdrawalRequestStatus {
/// @notice stETH token amount that was locked on withdrawal queue for this request
uint256 amountOfStETH;
/// @notice amount of stETH shares locked on withdrawal queue for this request
uint256 amountOfShares;
/// @notice address that can claim or transfer this request
address owner;
/// @notice timestamp of when the request was created, in seconds
uint256 timestamp;
/// @notice true, if request is finalized
bool isFinalized;
/// @notice true, if request is claimed. Request is claimable if (isFinalized && !isClaimed)
bool isClaimed;
}
function transferFrom(address _from, address _to, uint256 _requestId) external;
function ownerOf(uint256 _requestId) external returns (address);
function requestWithdrawals(uint256[] calldata _amounts, address _owner)
external
returns (uint256[] memory requestIds);
function getLastCheckpointIndex() external view returns (uint256);
function findCheckpointHints(uint256[] calldata _requestIds, uint256 _firstIndex, uint256 _lastIndex)
external
view
returns (uint256[] memory hintIds);
function claimWithdrawals(uint256[] calldata _requestIds, uint256[] calldata _hints) external;
function getWithdrawalStatus(uint256[] calldata _requestIds)
external
view
returns (WithdrawalRequestStatus[] memory statuses);
function getWithdrawalRequests(address _owner) external view returns (uint256[] memory requestsIds);
function getLastRequestId() external view returns (uint256);
}
interface IOracle {
function price(address asset) external view returns (uint256 price);
}
interface IHarvestable {
function collectRewards() external returns (address[] memory tokens, uint256[] memory rewards);
}
interface IMagpieRouter {
function swapWithMagpieSignature(bytes calldata) external payable returns (uint256 amountOut);
}
library DistributionTypes {
struct IncentivesProgramCreationInput {
string name;
address rewardToken;
uint104 emissionPerSecond;
uint40 distributionEnd;
}
}
library IDistributionManager {
struct AccruedRewards {
uint256 amount;
bytes32 programId;
address rewardToken;
}
}
interface SiloIncentivesControllerGaugeLike {
function claimRewards(address _to) external returns (IDistributionManager.AccruedRewards[] memory accruedRewards);
function createIncentivesProgram(DistributionTypes.IncentivesProgramCreationInput memory _incentivesProgramInput)
external;
function getAllProgramsNames() external view returns (string[] memory programsNames);
function getRewardsBalance(address _user, string memory _programName)
external
view
returns (uint256 unclaimedRewards);
function incentivesPrograms(bytes32)
external
view
returns (
uint256 index,
address rewardToken,
uint104 emissionPerSecond,
uint40 lastUpdateTimestamp,
uint40 distributionEnd
);
function owner() external view returns (address);
}
interface IEETHWithdrawal {
function requestWithdraw(address receipient, uint256 amount) external returns (uint256 requestId);
}
interface IEETHWithdrawalNFT {
function finalizeRequests(uint256 requestId) external;
function claimWithdraw(uint256 requestId) external;
function batchClaimWithdraw(uint256[] calldata requestIds) external;
}
interface IEETHRedemptionManager {
function redeemEEth(uint256 amount, address receiver) external;
function redeemWeEth(uint256 amount, address receiver) external;
function canRedeem(uint256 amount) external view returns (bool);
}
interface IWeETH {
function getEETHByWeETH(uint256 weETHAmount) external view returns (uint256);
function getWeETHByeETH(uint256 eETHAmount) external view returns (uint256);
function unwrap(uint256 weETHAmount) external returns (uint256);
}
interface IDistributor {
function claim(
address[] calldata users,
address[] calldata tokens,
uint256[] calldata amounts,
bytes32[][] calldata proofs
) external;
}
// Ethena Interfaces
struct UserCooldown {
uint104 cooldownEnd;
uint152 underlyingAmount;
}
interface IStakedUSDe is IERC4626 {
// Errors //
/// @notice Error emitted when the shares amount to redeem is greater than the shares balance of the owner
error ExcessiveRedeemAmount(); // 0x63345388
/// @notice Error emitted when the shares amount to withdraw is greater than the shares balance of the owner
error ExcessiveWithdrawAmount(); // 0xdf53dde2
function cooldownAssets(uint256 assets) external returns (uint256 shares);
function cooldownShares(uint256 shares) external returns (uint256 assets);
function unstake(address receiver) external;
function cooldowns(address receiver) external view returns (UserCooldown memory);
function getUnvestedAmount() external view returns (uint256);
function lastDistributionTimestamp() external view returns (uint256);
function transferInRewards(uint256 amount) external;
}
src/contracts/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
/**
* @title Base contract that provides ownership control
* @author Origin Protocol Inc
*/
contract Ownable {
error OnlyOwner(); // 0x5fc483c5
/// @notice The slot used to store the owner of the contract.
/// This is also used as the proxy admin.
/// keccak256(“eip1967.proxy.admin”) - 1 per EIP 1967
bytes32 internal constant OWNER_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
event AdminChanged(address previousAdmin, address newAdmin);
constructor() {
assert(OWNER_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setOwner(msg.sender);
}
/// @notice The contract owner and proxy admin.
function owner() public view returns (address) {
return _owner();
}
/// @notice Set the owner and proxy admin of the contract.
/// @param newOwner The address of the new owner.
function setOwner(address newOwner) external onlyOwner {
_setOwner(newOwner);
}
function _owner() internal view returns (address ownerOut) {
bytes32 position = OWNER_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
ownerOut := sload(position)
}
}
function _setOwner(address newOwner) internal {
emit AdminChanged(_owner(), newOwner);
bytes32 position = OWNER_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(position, newOwner)
}
}
function _onlyOwner() internal view {
if (msg.sender != _owner()) revert OnlyOwner();
}
modifier onlyOwner() {
_onlyOwner();
_;
}
}
src/contracts/OwnableOperable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {Ownable} from "./Ownable.sol";
/**
* @title Base contract that provides ownership and operational control
* @author Origin Protocol Inc
*/
contract OwnableOperable is Ownable {
error OnlyOperatorOrOwner(); // 0x3fbed347
/// @notice The account that can request and claim withdrawals.
address public operator;
uint256[49] private _gap;
event OperatorChanged(address newAdmin);
function _initOwnableOperable(address _operator) internal {
_setOperator(_operator);
}
/// @notice Set the account that can request and claim withdrawals.
/// @param newOperator The address of the new operator.
function setOperator(address newOperator) external onlyOwner {
_setOperator(newOperator);
}
function _setOperator(address newOperator) internal {
operator = newOperator;
emit OperatorChanged(newOperator);
}
modifier onlyOperatorOrOwner() {
if (msg.sender != operator && msg.sender != _owner()) revert OnlyOperatorOrOwner();
_;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"dependencies/@pendle-sy-1.0.0-1.0.0/:@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-4.9.3-4.9.3/contracts/",
"contracts/=src/contracts/",
"script/=script/",
"test/=test/",
"utils/=src/contracts/utils/",
"@solmate/=dependencies/solmate-6.7.0/src/",
"forge-std/=dependencies/forge-std-1.9.7/src/",
"@pendle-sy/=dependencies/@pendle-sy-1.0.0-1.0.0/contracts/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.0.2-5.0.2/contracts/",
"@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.0.2-5.0.2/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.