Latest 25 from a total of 165,721 transactions
| Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Deposit | 28808367 | 1 min ago | IN | 0 ETH | 0.0000043 | ||||
| Deposit | 28808365 | 1 min ago | IN | 0 ETH | 0.00000422 | ||||
| Deposit | 28808325 | 3 mins ago | IN | 0 ETH | 0.00000386 | ||||
| Deposit | 28808311 | 3 mins ago | IN | 0 ETH | 0.00000458 | ||||
| Deposit | 28808305 | 3 mins ago | IN | 0 ETH | 0.00000441 | ||||
| Withdraw | 28808272 | 4 mins ago | IN | 0 ETH | 0.00000426 | ||||
| Deposit | 28808212 | 6 mins ago | IN | 0 ETH | 0.00000412 | ||||
| Deposit | 28808091 | 10 mins ago | IN | 0 ETH | 0.0000042 | ||||
| Deposit | 28808046 | 11 mins ago | IN | 0 ETH | 0.00000407 | ||||
| Deposit | 28808036 | 11 mins ago | IN | 0 ETH | 0.00000465 | ||||
| Deposit | 28807975 | 13 mins ago | IN | 0 ETH | 0.00000419 | ||||
| Deposit | 28807952 | 14 mins ago | IN | 0 ETH | 0.0000044 | ||||
| Deposit | 28807951 | 14 mins ago | IN | 0 ETH | 0.00000413 | ||||
| Deposit | 28807936 | 14 mins ago | IN | 0 ETH | 0.0000046 | ||||
| Deposit | 28807779 | 18 mins ago | IN | 0 ETH | 0.00000426 | ||||
| Deposit | 28807525 | 25 mins ago | IN | 0 ETH | 0.00000424 | ||||
| Deposit | 28807455 | 27 mins ago | IN | 0 ETH | 0.0000047 | ||||
| Deposit | 28807376 | 29 mins ago | IN | 0 ETH | 0.00000446 | ||||
| Deposit | 28807356 | 30 mins ago | IN | 0 ETH | 0.00000406 | ||||
| Deposit | 28807333 | 31 mins ago | IN | 0 ETH | 0.00000413 | ||||
| Withdraw | 28807257 | 34 mins ago | IN | 0 ETH | 0.00000414 | ||||
| Deposit | 28807183 | 36 mins ago | IN | 0 ETH | 0.00000409 | ||||
| Deposit | 28807169 | 36 mins ago | IN | 0 ETH | 0.00000409 | ||||
| Deposit | 28807110 | 38 mins ago | IN | 0 ETH | 0.00000413 | ||||
| Deposit | 28807097 | 39 mins ago | IN | 0 ETH | 0.00000387 |
Latest 25 internal transactions (View All)
Advanced mode:
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 28806658 | 47 mins ago | 0.00019933 ETH | ||||
| 28785646 | 10 hrs ago | 0.0002894 ETH | ||||
| 28785053 | 10 hrs ago | 0.00030331 ETH | ||||
| 28783309 | 10 hrs ago | 0.00025018 ETH | ||||
| 28779688 | 12 hrs ago | 0.00021049 ETH | ||||
| 28768433 | 16 hrs ago | 0.00019883 ETH | ||||
| 28764667 | 18 hrs ago | 0.00019521 ETH | ||||
| 28752229 | 22 hrs ago | 0.00019528 ETH | ||||
| 28751496 | 22 hrs ago | 0.00019851 ETH | ||||
| 28748956 | 24 hrs ago | 0.00019773 ETH | ||||
| 28748182 | 24 hrs ago | 0.00019605 ETH | ||||
| 28726033 | 35 hrs ago | 0.00023451 ETH | ||||
| 28709673 | 41 hrs ago | 0.00020576 ETH | ||||
| 28709573 | 41 hrs ago | 0.00020576 ETH | ||||
| 28680275 | 2 days ago | 0.00020556 ETH | ||||
| 28680004 | 2 days ago | 0.00020556 ETH | ||||
| 28677842 | 2 days ago | 0.00020545 ETH | ||||
| 28677445 | 2 days ago | 0.0002079 ETH | ||||
| 28662493 | 2 days ago | 0.00023993 ETH | ||||
| 28650645 | 2 days ago | 0.00028034 ETH | ||||
| 28648974 | 2 days ago | 0.00023452 ETH | ||||
| 28637760 | 2 days ago | 0.00021558 ETH | ||||
| 28635370 | 2 days ago | 0.00021027 ETH | ||||
| 28619420 | 3 days ago | 0.00020242 ETH | ||||
| 28619370 | 3 days ago | 0.00020242 ETH |
Cross-Chain Transactions
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x2f950403...3629f1393 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
EtherFiLiquidModule
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 50 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { MessageHashUtils } from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { ReentrancyGuardTransient } from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import { IBoringOnChainQueue } from "../../interfaces/IBoringOnChainQueue.sol";
import { IEtherFiSafe } from "../../interfaces/IEtherFiSafe.sol";
import { WithdrawalRequest, SafeData } from "../../interfaces/ICashModule.sol";
import { IWETH } from "../../interfaces/IWETH.sol";
import { ILayerZeroTeller } from "../../interfaces/ILayerZeroTeller.sol";
import { IRoleRegistry } from "../../interfaces/IRoleRegistry.sol";
import { ModuleBase } from "../ModuleBase.sol";
import { ModuleCheckBalance } from "../ModuleCheckBalance.sol";
import { IBridgeModule } from "../../interfaces/IBridgeModule.sol";
/**
* @title EtherFiLiquidModule
* @author ether.fi
* @notice Module for interacting with ether.fi Liquid vaults
* @dev Extends ModuleBase to provide ether.fi Liquid integration for Safes
*/
contract EtherFiLiquidModule is ModuleBase, ModuleCheckBalance, ReentrancyGuardTransient, IBridgeModule {
using MessageHashUtils for bytes32;
using SafeCast for uint256;
/**
* @notice Stores cross-chain withdrawal request details
* @param destEid Destination endpoint ID for LayerZero
* @param asset Address of the liquid asset being bridged
* @param amount Amount of tokens to bridge
* @param destRecipient Recipient address on destination chain
*/
struct LiquidCrossChainWithdrawal {
uint32 destEid;
address asset;
uint256 amount;
address destRecipient;
}
/// @notice Address of the wrapped ETH contract
address public immutable weth;
/// @notice Mapping from liquid asset address to its corresponding teller contract
mapping(address asset => ILayerZeroTeller teller) public liquidAssetToTeller;
/// @notice Mapping of liquid token address to its withdraw config
mapping (address liquidToken => address boringQueue) public liquidWithdrawQueue;
/// @notice Cross-chain withdrawal requests for each Safe
mapping(address safe => LiquidCrossChainWithdrawal withdrawal) private withdrawals;
/// @notice TypeHash for deposit function signature
bytes32 public constant DEPOSIT_SIG = keccak256("deposit");
/// @notice TypeHash for withdraw function signature
bytes32 public constant WITHDRAW_SIG = keccak256("withdraw");
/// @notice TypeHash for bridge function signature
bytes32 public constant REQUEST_BRIDGE_SIG = keccak256("requestBridge");
/// @notice TypeHash for cancel bridge function signature
bytes32 public constant CANCEL_BRIDGE_SIG = keccak256("cancelBridge");
/// @notice Role identifier for admins of the Liquid Module
bytes32 public constant ETHERFI_LIQUID_MODULE_ADMIN = keccak256("ETHERFI_LIQUID_MODULE_ADMIN");
/// @notice Emitted when new liquid assets and their tellers are added to the module
event LiquidAssetsAdded(address[] liquidAssets, address[] tellers);
/// @notice Emitted when liquid assets are removed from the module
event LiquidAssetsRemoved(address[] liquidAssets);
/// @notice Emitted when safe deposits into Liquid
event LiquidDeposit(address indexed safe, address indexed inputToken, address indexed outputToken, uint256 inputAmount, uint256 outputAmount);
/// @notice Emitted when safe withdraws from Liquid
event LiquidWithdrawal(address indexed safe, address indexed liquidAsset, uint256 amountToWithdraw, uint256 amountOut);
/// @notice Emitted when safe bridge Liquid assets to other chains
event LiquidBridgeExecuted(address indexed safe, address indexed liquidAsset, address indexed destRecipient, uint32 destEid, uint256 amount, uint256 bridgeFee);
/// @notice Emitted when a request for bridging liquid assets is made
event LiquidBridgeRequested(address indexed safe, address indexed liquidAsset, uint32 destEid, address indexed destRecipient, uint256 amount);
/// @notice Emitted when a bridge request is cancelled
event LiquidBridgeCancelled(address indexed safe, address indexed liquidAsset, uint32 destEid, address indexed destRecipient, uint256 amount);
/**
* @notice Emitted when liquid asset withdraw config is set
* @param token Address of the liquid asset
* @param boringQueue Address of the boring queue
*/
event LiquidWithdrawQueueSet(address indexed token, address indexed boringQueue);
/// @notice Thrown when attempting to deposit to a liquid asset not supported by the module
error UnsupportedLiquidAsset();
/// @notice Thrown when the asset is not configured to accept deposits in the teller
error AssetNotSupportedForDeposit();
/// @notice Thrown when a caller lacks the proper authorization for an operation
error Unauthorized();
/// @notice Thrown when the teller configuration does not match the expected liquid asset
error InvalidConfiguration();
/// @notice Error for Invalid Owner quorum signatures
error InvalidSignatures();
/// @notice Error when native fee is insufficient
error InsufficientNativeFee();
/// @notice Error when native transfer fails
error NativeTransferFailed();
/// @notice Error when the return amount is less than min return
error InsufficientReturnAmount();
/// @notice Thrown when liquid withdraw config is not set for the liquid token
error LiquidWithdrawConfigNotSet();
/// @notice Thrown when the boring queue has a different boring vault than expected
error InvalidBoringQueue();
/// @notice Thrown when an address value is address(0)
error InvalidValue();
/// @notice Error thrown when no withdrawal is queued for Liquid
error NoWithdrawalQueuedForLiquid();
/// @notice Error thrown when no matching withdrawal is found for the safe
error CannotFindMatchingWithdrawalForSafe();
/**
* @notice Contract constructor
* @param _assets Addresses of the supported liquid assets
* @param _tellers Addresses of the Teller contracts for the liquid assets
* @param _etherFiDataProvider Address of the EtherFiDataProvider contract
* @param _weth Address of the wrapped ETH contract
* @dev Initializes the contract with supported liquid assets and their corresponding tellers
* @custom:throws ArrayLengthMismatch If the lengths of arrays mismatch
* @custom:throws InvalidInput If any provided address is zero
*/
constructor(address[] memory _assets, address[] memory _tellers, address _etherFiDataProvider, address _weth) ModuleBase(_etherFiDataProvider) ModuleCheckBalance(_etherFiDataProvider) {
uint256 len = _assets.length;
if (len != _tellers.length) revert ArrayLengthMismatch();
if (_etherFiDataProvider == address(0) || _weth == address(0)) revert InvalidInput();
weth = _weth;
for (uint256 i = 0; i < len; ) {
if (_assets[i] == address(0) || _tellers[i] == address(0)) revert InvalidInput();
if (address(ILayerZeroTeller(_tellers[i]).vault()) != _assets[i]) revert InvalidConfiguration();
liquidAssetToTeller[_assets[i]] = ILayerZeroTeller(_tellers[i]);
unchecked {
++i;
}
}
}
/**
* @notice Deposits tokens to a Liquid vault using signature verification
* @param safe The Safe address which holds the tokens
* @param assetToDeposit The address of the asset to deposit (or ETH address for ETH)
* @param liquidAsset The address of the liquid token to receive
* @param amountToDeposit The amount of tokens to deposit
* @param minReturn The minimum amount of liquid tokens to receive
* @param signer The address that signed the transaction
* @param signature The signature authorizing the transaction
* @dev Verifies signature then executes token approval and deposit through the Safe's module execution
* @custom:throws UnsupportedLiquidAsset If the liquid asset is not supported
* @custom:throws AssetNotSupportedForDeposit If the asset cannot be deposited to the teller
* @custom:throws InvalidInput If amount is zero
* @custom:throws OnlySafeAdmin If signer is not an admin of the Safe
* @custom:throws InvalidSignature If the signature is invalid
* @custom:throws InsufficientReturnAmount If the return amount is less than min return
*/
function deposit(address safe, address assetToDeposit, address liquidAsset, uint256 amountToDeposit, uint256 minReturn, address signer, bytes calldata signature) external onlyEtherFiSafe(safe) onlySafeAdmin(safe, signer) {
bytes32 digestHash = _getDepositDigestHash(safe, assetToDeposit, liquidAsset, amountToDeposit, minReturn);
_verifyAdminSig(digestHash, signer, signature);
_deposit(safe, assetToDeposit, liquidAsset, amountToDeposit, minReturn);
}
/**
* @dev Creates a digest hash for the deposit operation
* @param safe The Safe address which holds the tokens
* @param assetToDeposit The address of the asset to deposit
* @param liquidAsset The address of the liquid token
* @param amountToDeposit The amount to deposit
* @param minReturn The minimum amount of liquid tokens to receive
* @return The digest hash for signature verification
*/
function _getDepositDigestHash(address safe, address assetToDeposit, address liquidAsset, uint256 amountToDeposit, uint256 minReturn) internal returns (bytes32) {
return keccak256(abi.encodePacked(DEPOSIT_SIG, block.chainid, address(this), _useNonce(safe), safe, abi.encode(assetToDeposit, liquidAsset, amountToDeposit, minReturn))).toEthSignedMessageHash();
}
/**
* @dev Internal function to deposit assets to a Liquid vault
* @param safe The Safe address which holds the tokens
* @param assetToDeposit The address of the asset to deposit (or ETH address for ETH)
* @param liquidAsset The address of the liquid token to receive
* @param amountToDeposit The amount of tokens to deposit
* @param minReturn The minimum amount of liquid tokens to receive
* @custom:throws UnsupportedLiquidAsset If the liquid asset is not supported
* @custom:throws InvalidInput If amount or min return is zero
* @custom:throws AssetNotSupportedForDeposit If the asset cannot be deposited to the teller
* @custom:throws InsufficientReturnAmount If the return amount is less than min return
*/
function _deposit(address safe, address assetToDeposit, address liquidAsset, uint256 amountToDeposit, uint256 minReturn) internal {
ILayerZeroTeller teller = liquidAssetToTeller[liquidAsset];
if (address(teller) == address(0)) revert UnsupportedLiquidAsset();
if (amountToDeposit == 0 || minReturn == 0) revert InvalidInput();
_checkAmountAvailable(safe, assetToDeposit, amountToDeposit);
address[] memory to;
bytes[] memory data;
uint256[] memory values;
if (assetToDeposit == ETH) {
if (!teller.assetData(ERC20(weth)).allowDeposits) revert AssetNotSupportedForDeposit();
to = new address[](3);
data = new bytes[](3);
values = new uint256[](3);
to[0] = weth;
data[0] = abi.encodeWithSelector(IWETH.deposit.selector);
values[0] = amountToDeposit;
to[1] = weth;
data[1] = abi.encodeWithSelector(ERC20.approve.selector, address(liquidAsset), amountToDeposit);
to[2] = address(teller);
data[2] = abi.encodeWithSelector(ILayerZeroTeller.deposit.selector, ERC20(weth), amountToDeposit, minReturn);
} else {
if (!teller.assetData(ERC20(assetToDeposit)).allowDeposits) revert AssetNotSupportedForDeposit();
to = new address[](2);
data = new bytes[](2);
values = new uint256[](2);
to[0] = assetToDeposit;
data[0] = abi.encodeWithSelector(ERC20.approve.selector, address(liquidAsset), amountToDeposit);
to[1] = address(teller);
data[1] = abi.encodeWithSelector(ILayerZeroTeller.deposit.selector, ERC20(assetToDeposit), amountToDeposit, minReturn);
}
uint256 liquidTokenBalBefore = ERC20(liquidAsset).balanceOf(safe);
IEtherFiSafe(safe).execTransactionFromModule(to, values, data);
uint256 liquidTokenReceived = ERC20(liquidAsset).balanceOf(safe) - liquidTokenBalBefore;
if (liquidTokenReceived < minReturn) revert InsufficientReturnAmount();
emit LiquidDeposit(safe, assetToDeposit, liquidAsset, amountToDeposit, liquidTokenReceived);
}
/**
* @notice Withdraws from Liquid tokens from the safe
* @param safe The Safe address which holds the tokens
* @param liquidAsset The address of the liquid token to withdraw
* @param assetOut The address of the underlying token to receive
* @param amountToWithdraw The amount of tokens to withdraw
* @param minReturn Acceptable min return amount of asset out
* @param discount Acceptable discount in bps
* @param secondsToDeadline Expiry deadline in seconds from now
* @param signer The address that signed the transaction
* @param signature The signature authorizing the transaction
* @dev Verifies signature then executes token approval and deposit through the Safe's module execution
* @custom:throws LiquidWithdrawConfigNotSet If the liquid withdraw config is not set for the liquid token
* @custom:throws InvalidInput If the Safe doesn't have enough liquid asset balance
* @custom:throws OnlySafeAdmin If signer is not an admin of the Safe
* @custom:throws InvalidSignature If the signature is invalid
*/
function withdraw(address safe, address liquidAsset, address assetOut, uint128 amountToWithdraw, uint128 minReturn, uint16 discount, uint24 secondsToDeadline, address signer, bytes calldata signature) external onlyEtherFiSafe(safe) onlySafeAdmin(safe, signer) {
bytes32 digestHash = _getWithdrawDigestHash(safe, liquidAsset, assetOut, amountToWithdraw, minReturn, discount, secondsToDeadline);
_verifyAdminSig(digestHash, signer, signature);
_withdraw(safe, liquidAsset, assetOut, amountToWithdraw, minReturn, discount, secondsToDeadline);
}
/**
* @dev Creates a digest hash for the withdraw operation
* @param safe The Safe address which holds the tokens
* @param liquidAsset The address of the liquid token
* @param assetOut The address of the underlying token to receive
* @param amountToWithdraw The amount to withdraw
* @param minReturn Acceptable min return amount of asset out
* @param discount Acceptable discount in bps
* @param secondsToDeadline Expiry deadline in seconds from now
* @return The digest hash for signature verification
*/
function _getWithdrawDigestHash(address safe, address liquidAsset, address assetOut, uint128 amountToWithdraw, uint128 minReturn, uint16 discount, uint24 secondsToDeadline) internal returns (bytes32) {
return keccak256(abi.encodePacked(WITHDRAW_SIG, block.chainid, address(this), _useNonce(safe), safe, abi.encode(liquidAsset, assetOut, amountToWithdraw, minReturn, discount, secondsToDeadline))).toEthSignedMessageHash();
}
/**
* @notice Internal function which facilitates liquid withdrawals from the safe
* @param safe The Safe address which holds the tokens
* @param liquidAsset The address of the liquid token to withdraw
* @param assetOut The address of the underlying token to receive
* @param amountToWithdraw The amount of tokens to withdraw
* @param minReturn Acceptable min return amount of asset out
* @param discount Acceptable discount in bps
* @param secondsToDeadline Expiry deadline in seconds from now
* @custom:throws LiquidWithdrawConfigNotSet If the liquid withdraw config is not set for the liquid token
* @custom:throws InvalidInput If the Safe doesn't have enough liquid asset balance
* @custom:throws InvalidSignature If the signature is invalid
*/
function _withdraw(address safe, address liquidAsset, address assetOut, uint128 amountToWithdraw, uint128 minReturn, uint16 discount, uint24 secondsToDeadline) internal {
IBoringOnChainQueue boringQueue = IBoringOnChainQueue(liquidWithdrawQueue[liquidAsset]);
if (address(boringQueue) == address(0)) revert LiquidWithdrawConfigNotSet();
if (amountToWithdraw == 0) revert InvalidInput();
_checkAmountAvailable(safe, liquidAsset, amountToWithdraw);
uint128 amountOutFromQueue = boringQueue.previewAssetsOut(assetOut, amountToWithdraw, discount);
if (amountOutFromQueue < minReturn) revert InsufficientReturnAmount();
address[] memory to = new address[](2);
bytes[] memory data = new bytes[](2);
uint256[] memory values = new uint256[](2);
to[0] = liquidAsset;
data[0] = abi.encodeWithSelector(ERC20.approve.selector, boringQueue, amountToWithdraw);
to[1] = address(boringQueue);
data[1] = abi.encodeWithSelector(IBoringOnChainQueue.requestOnChainWithdraw.selector, assetOut, amountToWithdraw, discount, secondsToDeadline);
IEtherFiSafe(safe).execTransactionFromModule(to, values, data);
emit LiquidWithdrawal(safe, liquidAsset, amountToWithdraw, amountOutFromQueue);
}
/**
* @notice Gets the pending bridge request for a safe
* @param safe Address of the EtherFiSafe
* @return LiquidCrossChainWithdrawal containing the pending bridge request details
*/
function getPendingBridge(address safe) external view returns (LiquidCrossChainWithdrawal memory) {
return withdrawals[safe];
}
/**
* @notice Requests bridging of liquid assets from one chain to another
* @param safe The Safe address which holds the tokens
* @param destEid The destination chain ID in LayerZero format
* @param asset The address of the liquid asset to bridge
* @param amount The amount of liquid assets to bridge
* @param destRecipient The recipient address on the destination chain
* @param signers Array of addresses that signed the transaction
* @param signatures Array of signatures from the signers
* @custom:throws InvalidSignatures If the signatures are invalid
* @custom:throws UnsupportedLiquidAsset If the liquid asset is not supported
* @custom:throws InvalidInput If the destRecipient is address(0)
*/
function requestBridge(address safe, uint32 destEid, address asset, uint256 amount, address destRecipient, address[] calldata signers, bytes[] calldata signatures) external payable nonReentrant onlyEtherFiSafe(safe) {
_checkBridgeSignature(safe, asset, destEid, destRecipient, amount, signers, signatures);
_requestBridge(safe, asset, destEid, destRecipient, amount);
}
/**
* @notice Executes a previously requested bridge transaction
* @param safe The Safe address that requested the bridge
* @dev Verifies the withdrawal request matches the stored bridge details before execution
* @custom:throws NoWithdrawalQueuedForLiquid If no bridge request exists for the safe
* @custom:throws CannotFindMatchingWithdrawalForSafe If the withdrawal details don't match
*/
function executeBridge(address safe) public payable nonReentrant onlyEtherFiSafe(safe) {
LiquidCrossChainWithdrawal memory withdrawal = withdrawals[safe];
if (withdrawal.destRecipient == address(0)) revert NoWithdrawalQueuedForLiquid();
WithdrawalRequest memory withdrawalRequest = cashModule.getData(safe).pendingWithdrawalRequest;
if (withdrawalRequest.recipient != address(this) || withdrawalRequest.tokens.length != 1 || withdrawalRequest.tokens[0] != withdrawal.asset || withdrawalRequest.amounts[0] != withdrawal.amount) revert CannotFindMatchingWithdrawalForSafe();
cashModule.processWithdrawal(safe);
_bridge(safe, withdrawal.asset, withdrawal.destEid, withdrawal.destRecipient, withdrawal.amount);
delete withdrawals[safe];
}
/**
* @notice Cancels a bridge request for a safe
* @param safe Address of the EtherFiSafe
* @param signers Array of addresses of safe owners that signed the transaction
* @param signatures Array of signatures from the signers
*/
function cancelBridge(address safe, address[] calldata signers, bytes[] calldata signatures) external nonReentrant onlyEtherFiSafe(safe) {
_checkCancelBridgeSignature(safe, signers, signatures);
LiquidCrossChainWithdrawal memory withdrawal = withdrawals[safe];
if (withdrawal.destRecipient == address(0)) revert NoWithdrawalQueuedForLiquid();
SafeData memory data = cashModule.getData(safe);
// If there is a withdrawal pending from this module on Cash Module, cancel it
if (data.pendingWithdrawalRequest.recipient == address(this)) cashModule.cancelWithdrawalByModule(safe);
if (withdrawals[safe].asset != address(0)) {
emit LiquidBridgeCancelled(safe, withdrawal.asset, withdrawal.destEid, withdrawal.destRecipient, withdrawal.amount);
delete withdrawals[safe];
}
}
/**
* @notice Cancels a bridge request by the cash module
* @dev This function is intended to be called by the cash module to cancel a bridge
* @param safe Address of the EtherFiSafe
*/
function cancelBridgeByCashModule(address safe) external {
if (msg.sender != etherFiDataProvider.getCashModule()) revert Unauthorized();
LiquidCrossChainWithdrawal memory withdrawal = withdrawals[safe];
// Return if no withdrawal found for Liquid
if (withdrawal.destRecipient == address(0)) return;
emit LiquidBridgeCancelled(safe, withdrawal.asset, withdrawal.destEid, withdrawal.destRecipient, withdrawal.amount);
delete withdrawals[safe];
}
/**
* @notice Returns the bridge fee for bridging liquid asset
* @param liquidAsset Address of the liquid asset
* @param destEid The destination chain ID in LayerZero format
* @param destRecipient The recipient address on the destination chain
* @param amount The amount of liquid assets to bridge
* @return The bridge fee for the liquid asset withdrawal queued for the safe
*/
function getBridgeFee(address liquidAsset, uint32 destEid, address destRecipient, uint256 amount) public view returns(uint256) {
ILayerZeroTeller teller = liquidAssetToTeller[liquidAsset];
if (address(teller) == address(0)) revert UnsupportedLiquidAsset();
bytes memory bridgeWildCard = abi.encode(destEid);
return teller.previewFee(amount.toUint96(), destRecipient, bridgeWildCard, ERC20(ETH));
}
/**
* @notice Returns the bridge fee for the liquid asset withdrawal queued for the safe
* @param safe Address of the EtherFiSafe
* @return The bridge fee for the liquid asset withdrawal queued for the safe
* @custom:throws NoWithdrawalQueuedForLiquid If no withdrawal is queued for the safe
* @custom:throws UnsupportedLiquidAsset If the liquid asset is not supported
*/
function getBridgeFeeForSafe(address safe) external view returns(uint256) {
LiquidCrossChainWithdrawal memory withdrawal = withdrawals[safe];
if (withdrawal.destRecipient == address(0)) revert NoWithdrawalQueuedForLiquid();
return getBridgeFee(withdrawal.asset, withdrawal.destEid, withdrawal.destRecipient, withdrawal.amount);
}
/**
* @dev Verifies that the transaction has been properly signed by the required signers
* @param safe Address of the EtherFiSafe
* @param liquidAsset Address of the liquid asset to bridge
* @param destEid Destination chain ID
* @param destRecipient Recipient address on the destination chain
* @param amount Amount of the asset to bridge
* @param signers Array of addresses that signed the transaction
* @param signatures Array of signatures from the signers
* @custom:throws InvalidSignatures if the signatures are invalid
*/
function _checkBridgeSignature(address safe, address liquidAsset, uint32 destEid, address destRecipient, uint256 amount, address[] calldata signers, bytes[] calldata signatures) internal {
bytes32 digestHash = keccak256(abi.encodePacked(REQUEST_BRIDGE_SIG, block.chainid, address(this), IEtherFiSafe(safe).useNonce(), safe, abi.encode(liquidAsset, destEid, destRecipient, amount))).toEthSignedMessageHash();
if (!IEtherFiSafe(safe).checkSignatures(digestHash, signers, signatures)) revert InvalidSignatures();
}
function _checkCancelBridgeSignature(address safe, address[] calldata signers, bytes[] calldata signatures) internal {
bytes32 digestHash = keccak256(abi.encodePacked(CANCEL_BRIDGE_SIG, block.chainid, address(this), IEtherFiSafe(safe).useNonce(), safe)).toEthSignedMessageHash();
if (!IEtherFiSafe(safe).checkSignatures(digestHash, signers, signatures)) revert InvalidSignatures();
}
function _requestBridge(address safe, address liquidAsset, uint32 destEid, address destRecipient, uint256 amount) internal {
if (liquidAsset == address(0) || amount == 0 || destRecipient == address(0)) revert InvalidInput();
ILayerZeroTeller teller = liquidAssetToTeller[liquidAsset];
if (address(teller) == address(0)) revert UnsupportedLiquidAsset();
cashModule.requestWithdrawalByModule(safe, liquidAsset, amount);
emit LiquidBridgeRequested(safe, liquidAsset, destEid, destRecipient, amount);
(uint64 withdrawalDelay, , ) = cashModule.getDelays();
if (withdrawalDelay == 0) {
_bridge(safe, liquidAsset, destEid, destRecipient, amount);
} else {
withdrawals[safe] = LiquidCrossChainWithdrawal({
destEid: destEid,
asset: liquidAsset,
amount: amount,
destRecipient: destRecipient
});
}
}
/**
* @dev Internal function to execute a bridge transaction
* @param safe The Safe address which holds the tokens
* @param liquidAsset The address of the liquid asset to bridge
* @param destEid The destination chain ID in LayerZero format
* @param destRecipient The recipient address on the destination chain
* @param amount The amount of liquid asset to bridge (will be cast to uint96)
* @custom:throws UnsupportedLiquidAsset If the liquid asset is not supported
* @custom:throws InsufficientNativeFee If the provided native fee is insufficient
*/
function _bridge(address safe, address liquidAsset, uint32 destEid, address destRecipient, uint256 amount) internal {
ILayerZeroTeller teller = liquidAssetToTeller[liquidAsset];
if (address(teller) == address(0)) revert UnsupportedLiquidAsset();
bytes memory bridgeWildCard = abi.encode(destEid);
uint256 fee = teller.previewFee(amount.toUint96(), destRecipient, bridgeWildCard, ERC20(ETH));
if (address(this).balance < fee) revert InsufficientNativeFee();
teller.bridge{value: fee}(amount.toUint96(), destRecipient, bridgeWildCard, ERC20(ETH), fee);
emit LiquidBridgeExecuted(safe, liquidAsset, destRecipient, destEid, amount, fee);
}
/**
* @notice Adds new liquid assets and their corresponding tellers to the module
* @param liquidAssets Array of liquid asset addresses to add
* @param tellers Array of teller addresses corresponding to the liquid assets
* @dev Only callable by accounts with the ETHERFI_LIQUID_MODULE_ADMIN role
* @custom:throws Unauthorized If caller doesn't have the admin role
* @custom:throws ArrayLengthMismatch If the lengths of arrays mismatch
* @custom:throws InvalidInput If any provided address is zero or the array is empty
* @custom:throws InvalidConfiguration If a teller's vault doesn't match the expected liquid asset
*/
function addLiquidAssets(address[] calldata liquidAssets, address[] calldata tellers) external {
if (!etherFiDataProvider.roleRegistry().hasRole(ETHERFI_LIQUID_MODULE_ADMIN, msg.sender)) revert Unauthorized();
uint256 len = liquidAssets.length;
if (len != tellers.length) revert ArrayLengthMismatch();
if (len == 0) revert InvalidInput();
for (uint256 i = 0; i < len; ) {
if (liquidAssets[i] == address(0) || tellers[i] == address(0)) revert InvalidInput();
if (address(ILayerZeroTeller(tellers[i]).vault()) != liquidAssets[i]) revert InvalidConfiguration();
liquidAssetToTeller[liquidAssets[i]] = ILayerZeroTeller(tellers[i]);
unchecked {
++i;
}
}
emit LiquidAssetsAdded(liquidAssets, tellers);
}
/**
* @notice Removes liquid assets from the module
* @param liquidAssets Array of liquid asset addresses to remove
* @dev Only callable by accounts with the ETHERFI_LIQUID_MODULE_ADMIN role
* @custom:throws Unauthorized If caller doesn't have the admin role
* @custom:throws InvalidInput If the array is empty
*/
function removeLiquidAsset(address[] calldata liquidAssets) external {
if (!etherFiDataProvider.roleRegistry().hasRole(ETHERFI_LIQUID_MODULE_ADMIN, msg.sender)) revert Unauthorized();
uint256 len = liquidAssets.length;
if (len == 0) revert InvalidInput();
for (uint256 i = 0; i < len; ) {
delete liquidAssetToTeller[liquidAssets[i]];
unchecked {
++i;
}
}
emit LiquidAssetsRemoved(liquidAssets);
}
/**
* @notice Function to set the liquid asset withdraw queue
* @dev Only callable by the role registry owner
* @param asset Address of the liquid asset
* @param boringQueue Address of the boring queue
* @custom:throws InvalidValue If any address parameter is zero
* @custom:throws InvalidBoringQueue If the queue does not belong to the liquid asset
*/
function setLiquidAssetWithdrawQueue(address asset, address boringQueue) external {
if (!etherFiDataProvider.roleRegistry().hasRole(ETHERFI_LIQUID_MODULE_ADMIN, msg.sender)) revert Unauthorized();
if (asset == address(0) || boringQueue == address(0)) revert InvalidValue();
if (asset != address(IBoringOnChainQueue(boringQueue).boringVault())) revert InvalidBoringQueue();
liquidWithdrawQueue[asset] = boringQueue;
emit LiquidWithdrawQueueSet(asset, boringQueue);
}
/**
* @notice Returns the liquid asset withdraw queue
* @param asset Address of the liquid asset
* @return Boring Queue for liquid asset
*/
function getLiquidAssetWithdrawQueue(address asset) external view returns (address) {
return liquidWithdrawQueue[asset];
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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/bool 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);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @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 {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @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) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IBoringOnChainQueue {
/**
* @param allowWithdraws Whether or not withdraws are allowed for this asset.
* @param secondsToMaturity The time in seconds it takes for the asset to mature.
* @param minimumSecondsToDeadline The minimum time in seconds a withdraw request must be valid for before it is expired
* @param minDiscount The minimum discount allowed for a withdraw request.
* @param maxDiscount The maximum discount allowed for a withdraw request.
* @param minimumShares The minimum amount of shares that can be withdrawn.
*/
struct WithdrawAsset {
bool allowWithdraws;
uint24 secondsToMaturity;
uint24 minimumSecondsToDeadline;
uint16 minDiscount;
uint16 maxDiscount;
uint96 minimumShares;
}
/**
* @notice Gets the withdrawal config for the asset out
* @param assetOut Address of asset out
* @return WithdrawAsset struct
*/
function withdrawAssets(address assetOut) external view returns (WithdrawAsset memory);
/**
* @notice Returns the boring vault address
*/
function boringVault() external view returns (BoringVault);
/**
* @notice Request an on-chain withdraw.
* @param assetOut The asset to withdraw.
* @param amountOfShares The amount of shares to withdraw.
* @param discount The discount to apply to the withdraw in bps.
* @param secondsToDeadline The time in seconds the request is valid for.
* @return requestId The request Id.
*/
function requestOnChainWithdraw(address assetOut, uint128 amountOfShares, uint16 discount, uint24 secondsToDeadline) external returns (bytes32 requestId);
/**
* @notice Preview assets out from a withdraw request.
* @param assetOut The asset to withdraw.
* @param amountOfShares The amount of shares to withdraw.
* @param discount The discount to apply to the withdraw in bps.
* @return amountOfAssets128 Amount of assets out.
*/
function previewAssetsOut(address assetOut, uint128 amountOfShares, uint16 discount) external view returns (uint128 amountOfAssets128);
}
contract BoringVault {}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IEtherFiSafe {
/**
* @notice Verifies signatures against a digest hash until reaching the required threshold
* @param digestHash The hash of the data that was signed
* @param signers Array of addresses that supposedly signed the message
* @param signatures Array of signatures corresponding to the signers
* @return bool True if enough valid signatures are found to meet the threshold
* @dev Processes signatures until threshold is met. Invalid signatures are skipped.
* @custom:throws EmptySigners If the signers array is empty
* @custom:throws ArrayLengthMismatch If the lengths of signers and signatures arrays do not match
* @custom:throws InsufficientSigners If the length of signers array is less than the required threshold
* @custom:throws DuplicateElementFound If the signers array contains duplicate addresses
* @custom:throws InvalidSigner If a signer is the zero address or not an owner of the safe
*/
function checkSignatures(bytes32 digestHash, address[] calldata signers, bytes[] calldata signatures) external view returns (bool);
/**
* @notice Executes a transaction from an authorized module
* @dev Allows modules to execute arbitrary transactions on behalf of the safe
* @param to Array of target addresses for the calls
* @param values Array of ETH values to send with each call
* @param data Array of calldata for each call
* @custom:throws OnlyModules If the caller is not an enabled module
* @custom:throws CallFailed If any of the calls fail
*/
function execTransactionFromModule(address[] calldata to, uint256[] calldata values, bytes[] calldata data) external;
/**
* @notice Gets the current nonce value
* @dev Used for replay protection in signatures
* @return Current nonce value
*/
function nonce() external view returns (uint256);
/**
* @notice Returns all current owners of the safe
* @dev Implementation of the abstract function from ModuleManager
* @return address[] Array containing all owner addresses
*/
function getOwners() external view returns (address[] memory);
/**
* @notice Uses a nonce for operations in modules which require a quorum of owners
* @dev Can only be called by enabled modules
* @return uint256 The current nonce value before incrementing
* @custom:throws OnlyModules If the caller is not an enabled module
*/
function useNonce() external returns (uint256);
function isAdmin(address account) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { EnumerableSetLib } from "solady/utils/EnumerableSetLib.sol";
import { IDebtManager } from "../interfaces/IDebtManager.sol";
import { IEtherFiDataProvider } from "../interfaces/IEtherFiDataProvider.sol";
import { IPriceProvider } from "../interfaces/IPriceProvider.sol";
import { SpendingLimit, SpendingLimitLib } from "../libraries/SpendingLimitLib.sol";
/**
* @title CashbackTypes
* @notice Defines the different cashback types
*/
enum CashbackTypes {
Regular,
Spender,
Promotion,
Referral
}
/**
* @title Cashback
* @notice Defines the structure of Cashback
*/
struct Cashback {
address to;
CashbackTokens[] cashbackTokens;
}
/**
* @title CashbackTokens
* @notice Defines the structure of Cashback tokens
*/
struct CashbackTokens {
address token;
uint256 amountInUsd;
CashbackTypes cashbackType;
}
/**
* @title TokenDataInUsd
* @notice Defines the token data with amount in USD
*/
struct TokenDataInUsd {
address token;
uint256 amountInUsd;
}
/**
* @title BinSponsor
* @notice Defines the bin sponsors or card issuers
*/
enum BinSponsor {
Reap,
Rain
}
/**
* @title Mode
* @notice Defines the operating mode for cash spending operations
* @dev Credit mode borrows tokens, Debit mode uses balance from the safe
*/
enum Mode {
Credit,
Debit
}
/**
* @title WithdrawalRequest
* @notice Structure representing a pending withdrawal of tokens
* @dev Includes tokens, amounts, recipient, and finalization timestamp
*/
struct WithdrawalRequest {
address[] tokens;
uint256[] amounts;
address recipient;
uint96 finalizeTime;
}
/**
* @title SafeData
* @notice View-only representation of a Safe's cash configuration
* @dev Used for returning Safe data in external-facing functions
*/
struct SafeData {
/// @notice Spend limit for the user
SpendingLimit spendingLimit;
/// @notice Impending withdrawal request for the user
WithdrawalRequest pendingWithdrawalRequest;
/// @notice User's chosen mode
Mode mode;
/// @notice Start time for incoming mode
uint256 incomingModeStartTime;
/// @notice Running total of all cashback earned by this safe (and its spenders) in USD
uint256 totalCashbackEarnedInUsd;
/// @notice Incoming mode that will be applied after the delay
Mode incomingMode;
}
/**
* @notice SafeTiers
* @dev Gets cashback based on the safe tier
*/
enum SafeTiers {
Pepe,
Wojak,
Chad,
Whale,
Business
}
/**
* @title SafeCashConfig
* @notice Complete storage representation of a Safe's cash configuration
* @dev Includes all data needed for managing a Safe's cash operations
*/
struct SafeCashConfig {
/// @notice Spending limit configuration including daily and monthly limits
SpendingLimit spendingLimit;
/// @notice Pending withdrawal request with token addresses, amounts, recipient, and finalization time
WithdrawalRequest pendingWithdrawalRequest;
/// @notice Current operating mode (Credit or Debit) for spending transactions
Mode mode;
/// @notice Timestamp when a pending change to incoming mode will take effect (0 if no pending change)
uint256 incomingModeStartTime;
/// @notice Tier level of the safe that determines cashback percentages
SafeTiers safeTier;
/// @notice Mapping of transaction IDs to cleared status to prevent replay attacks
mapping(bytes32 txId => bool cleared) transactionCleared;
/// @notice Percentage of cashback allocated to the safe vs. the spender (in basis points, 5000 = 50%)
uint256 DEPRECATED_cashbackSplitToSafePercentage;
/// @notice Running total of all cashback earned by this safe (and its spenders) in USD
uint256 totalCashbackEarnedInUsd;
/// @notice Incoming mode that will be applied after the delay
Mode incomingMode;
}
/**
* @title SafeCashData
* @notice Comprehensive data structure for front-end display of Safe cash state
* @dev Aggregates data from multiple sources for a complete view of a Safe's financial state
*/
struct SafeCashData {
/// @notice Current operating mode (Credit or Debit)
Mode mode;
/// @notice Array of collateral token balances
IDebtManager.TokenData[] collateralBalances;
/// @notice Array of borrowed token balances
IDebtManager.TokenData[] borrows;
/// @notice Array of token prices
IDebtManager.TokenData[] tokenPrices;
/// @notice Current withdrawal request
WithdrawalRequest withdrawalRequest;
/// @notice Total value of collateral in USD
uint256 totalCollateral;
/// @notice Total value of borrows in USD
uint256 totalBorrow;
/// @notice Maximum borrowing power in USD
uint256 maxBorrow;
/// @notice Maximum spendable amount in Credit mode (USD)
uint256 creditMaxSpend;
/// @notice Remaining spending limit allowance
uint256 spendingLimitAllowance;
/// @notice Running total of all cashback earned by this safe (and its spenders) in USD
uint256 totalCashbackEarnedInUsd;
/// @notice Timestamp when a pending change to incoming mode mode will take effect (0 if no pending change)
uint256 incomingModeStartTime;
/// @notice Maximum spendable amount in Debit mode
DebitModeMaxSpend debitMaxSpend;
}
/**
* @title DebitModeMaxSpend
* @notice Data structure to return Debit mode max spend result
*/
struct DebitModeMaxSpend {
/// @notice Tokens that can be spent. Order of token matter, Order determines
/// priority for deficit coverage - earlier tokens are used first
address[] spendableTokens;
/// @notice Amounts of respective tokens that can be spent
uint256[] spendableAmounts;
/// @notice Amounts in USD of respective tokens that can be spent
uint256[] amountsInUsd;
/// @notice Total amount in USD that can be spent
uint256 totalSpendableInUsd;
}
interface ICashModule {
/// @notice Error thrown when a transaction has already been cleared
error TransactionAlreadyCleared();
/// @notice Error thrown when a non-EtherFi wallet tries to access restricted functions
error OnlyEtherFiWallet();
/// @notice Error thrown when an unsupported token is used
error UnsupportedToken();
/// @notice Error thrown when a token that is not a borrow token is used in certain operations
error OnlyBorrowToken();
/// @notice Error thrown when an operation amount is zero
error AmountZero();
/// @notice Error thrown when a balance is insufficient for an operation
error InsufficientBalance();
/// @notice Error thrown when borrowings would exceed maximum allowed after a spending operation
error BorrowingsExceedMaxBorrowAfterSpending();
/// @notice Error thrown when a recipient address is zero
error RecipientCannotBeAddressZero();
/// @notice Error thrown when caller doesn't have the Cash Module Controller role
error OnlyCashModuleController();
/// @notice Error thrown when a withdrawal is attempted before the delay period
error CannotWithdrawYet();
/// @notice Error thrown when signature verification fails
error InvalidSignatures();
/// @notice Error thrown when trying to set a mode that's already active
error ModeAlreadySet();
/// @notice Error thrown when a non-DebtManager contract calls restricted functions
error OnlyDebtManager();
/// @notice Error thrown when trying to set a tier that's already set
error AlreadyInSameTier(uint256 index);
/// @notice Error thrown when a cashback percentage exceeds max allowed
error CashbackPercentageGreaterThanMaxAllowed();
/// @notice Error thrown when trying to set a split percentage that's already set
error SplitAlreadyTheSame();
/// @notice Throws when the msg.sender is not an admin to the safe
error OnlySafeAdmin();
/// @notice Thrown when the input is invalid
error InvalidInput();
/// @notice Thrown when the signature verification fails
error InvalidSignature();
/// @notice Thrown when there is an array length mismatch
error ArrayLengthMismatch();
/// @notice Thrown when the caller is not an EtherFi Safe
error OnlyEtherFiSafe();
/// @notice Error thrown when trying to use multiple tokens in credit mode
error OnlyOneTokenAllowedInCreditMode();
/// @notice Error thrown when trying to withdraw an non whitelisted asset
/// @param asset The address of the invalid asset
error InvalidWithdrawAsset(address asset);
/// @notice Error thrown when a withdrawal request is made by a module that is not whitelisted
error OnlyWhitelistedModuleCanRequestWithdraw();
/// @notice Error thrown when a module tries to process a withdrawal that was not requested by it
error OnlyModuleThatRequestedCanWithdraw();
/// @notice Error thrown when a module tries to cancel a withdrawal that was not requested by it
error OnlyModuleThatRequestedCanCancel();
/// @notice Error thrown when a withdrawal request does not exist for a safe
error WithdrawalDoesNotExist();
/// @notice Error thrown when a module is not whitelisted on the data provider
error ModuleNotWhitelistedOnDataProvider();
/// @notice Error thrown when a withdrawal request is made by an invalid address or to an invalid recipient
error InvalidWithdrawRequest();
/**
* @notice Role identifier for EtherFi wallet access control
* @return The role identifier as bytes32
*/
function ETHER_FI_WALLET_ROLE() external pure returns (bytes32);
/**
* @notice Role identifier for Cash Module controller access
* @return The role identifier as bytes32
*/
function CASH_MODULE_CONTROLLER_ROLE() external pure returns (bytes32);
/**
* @notice Maximum allowed cashback percentage (10%)
* @return The maximum percentage in basis points
*/
function MAX_CASHBACK_PERCENTAGE() external pure returns (uint256);
/**
* @notice Represents 100% in basis points (10,000)
* @return 100% value in basis points
*/
function HUNDRED_PERCENT_IN_BPS() external pure returns (uint256);
/**
* @notice Returns all the assets whitelisted for withdrawals
* @return Array of whitelisted withdraw assets
*/
function getWhitelistedWithdrawAssets() external view returns (address[] memory);
/**
* @notice Retrieves cash configuration data for a Safe
* @param safe Address of the EtherFi Safe
* @return Data structure containing Safe cash configuration
* @custom:throws OnlyEtherFiSafe if the address is not a valid EtherFi Safe
*/
function getData(address safe) external view returns (SafeData memory);
/**
* @notice Checks if a transaction has been cleared
* @param safe Address of the EtherFi Safe
* @param txId Transaction identifier
* @return Boolean indicating if the transaction is cleared
* @custom:throws OnlyEtherFiSafe if the address is not a valid EtherFi Safe
*/
function transactionCleared(address safe, bytes32 txId) external view returns (bool);
/**
* @notice Gets the debt manager contract
* @return IDebtManager instance
*/
function getDebtManager() external view returns (IDebtManager);
/**
* @notice Gets the settlement dispatcher address
* @dev The settlement dispatcher receives the funds that are spent
* @param binSponsor Bin sponsor for which the settlement dispatcher needs to be returned
* @return settlementDispatcher The address of the settlement dispatcher
*/
function getSettlementDispatcher(BinSponsor binSponsor) external view returns (address settlementDispatcher);
/**
* @notice Returns the EtherFiDataProvider contract reference
* @dev Used to access global system configuration and services
* @return The EtherFiDataProvider contract instance
*/
function etherFiDataProvider() external view returns (IEtherFiDataProvider);
/**
* @notice Gets the pending cashback amount for an account in USD
* @dev Returns the amount of cashback waiting to be claimed
* @param account Address of the account (safe or spender)
* @param tokens Addresses of tokens for cashback
* @return data Pending cashback data for tokens in USD
* @return totalCashbackInUsd Total pending cashback amount in USD
*/
function getPendingCashback(address account, address[] memory tokens) external view returns (TokenDataInUsd[] memory data, uint256 totalCashbackInUsd);
/**
* @notice Gets the pending cashback amount for an account in USD for a specific token
* @dev Returns the amount of cashback waiting to be claimed
* @param account Address of the account (safe or spender)
* @param token Address of tokens for cashback
* @return Pending cashback amount in USD for the token
*/
function getPendingCashbackForToken(address account, address token) external view returns (uint256);
/**
* @notice Gets the current delay settings for the module
* @return withdrawalDelay Delay in seconds before a withdrawal can be finalized
* @return spendLimitDelay Delay in seconds before spending limit changes take effect
* @return modeDelay Delay in seconds before a mode change takes effect
*/
function getDelays() external view returns (uint64, uint64, uint64);
/**
* @notice Gets the current operating mode of a safe
* @dev Considers pending mode changes that have passed their delay
* @param safe Address of the EtherFi Safe
* @return The current operating mode (Debit or Credit)
*/
function getMode(address safe) external view returns (Mode);
/**
* @notice Gets the timestamp when a pending mode change will take effect
* @dev Returns 0 if no pending change or if the safe uses debit mode
* @param safe Address of the EtherFi Safe
* @return Timestamp when incoming mode will take effect, or 0 if not applicable
*/
function incomingModeStartTime(address safe) external view returns (uint256);
/**
* @notice Gets the pending withdrawal amount for a token
* @dev Only callable for valid EtherFi Safe addresses
* @param safe Address of the EtherFi Safe
* @param token Address of the token to check
* @return Amount of tokens pending withdrawal
* @custom:throws OnlyEtherFiSafe if the address is not a valid EtherFi Safe
*/
function getPendingWithdrawalAmount(address safe, address token) external view returns (uint256);
/**
* @notice Returns the list of modules that can request withdrawals
* @return Array of module addresses that can request withdrawals
*/
function getWhitelistedModulesCanRequestWithdraw() external view returns (address[] memory);
/**
* @notice Sets up a new Safe's Cash Module with initial configuration
* @dev Creates default spending limits and sets initial mode to Debit with 50% cashback split
* @param data The encoded initialization data containing daily limit, monthly limit, and timezone offset
* @custom:throws OnlyEtherFiSafe if the caller is not a valid EtherFi Safe
*/
function setupModule(bytes calldata data) external;
/**
* @notice Initializes the CashModule contract
* @dev Sets up the role registry, debt manager, settlement dispatcher, and data providers
* @param _roleRegistry Address of the role registry contract
* @param _debtManager Address of the debt manager contract
* @param _settlementDispatcherReap Address of the settlement dispatcher for Reap
* @param _settlementDispatcherRain Address of the settlement dispatcher for Rain
* @param _cashbackDispatcher Address of the cashback dispatcher
* @param _cashEventEmitter Address of the cash event emitter
* @param _cashModuleSetters Address of the cash module setters contract
* @custom:throws InvalidInput if any essential address is zero
*/
function initialize(address _roleRegistry, address _debtManager, address _settlementDispatcherReap, address _settlementDispatcherRain, address _cashbackDispatcher, address _cashEventEmitter, address _cashModuleSetters) external;
/**
* @notice Cancel a pending withdrawal request
* @dev Only callable by the module that requested the withdrawal if requested by a whitelisted module
* @param safe Address of the EtherFi Safe
* @param signers Array of signers for the cancellation
* @param signatures Array of signatures from the signers
*/
function cancelWithdrawal(address safe, address[] calldata signers, bytes[] calldata signatures) external;
/**
* @notice Cancels a pending withdrawal request by the module
* @dev Only callable by whitelisted modules that requested the withdrawal
* @param safe Address of the EtherFi Safe
*/
function cancelWithdrawalByModule(address safe) external;
/**
* @notice Requests a withdrawal of a token by a module on behalf of a safe
* @dev Can only be called by whitelisted modules
* @param safe Address of the EtherFi Safe
* @param token Token address to withdraw
* @param amount Token amount to withdraw
* @custom:throws OnlyEtherFiSafe if the caller is not a valid EtherFi Safe
* @custom:throws OnlyWhitelistedModuleCanRequestWithdraw if the caller is not a whitelisted module
*/
function requestWithdrawalByModule(address safe, address token, uint256 amount) external;
/**
* @notice Configures which modules can request withdrawals
* @dev Can only be called by the CASH_MODULE_CONTROLLER_ROLE
* @param modules Array of module addresses to configure
* @param shouldWhitelist Array of boolean values indicating whether to whitelist each module
*/
function configureModulesCanRequestWithdraw(address[] calldata modules, bool[] calldata shouldWhitelist) external;
/**
* @notice Configures the withdraw assets whitelist
* @dev Only callable by accounts with CASH_MODULE_CONTROLLER_ROLE
* @param assets Array of asset addresses to configure
* @param shouldWhitelist Array of boolean suggesting whether to whitelist the assets
* @custom:throws OnlyCashModuleController if the caller does not have CASH_MODULE_CONTROLLER_ROLE role
* @custom:throws InvalidInput If the arrays are empty
* @custom:throws ArrayLengthMismatch If the arrays have different lengths
* @custom:throws InvalidAddress If any address is the zero address
* @custom:throws DuplicateElementFound If any address appears more than once in the addrs array
*/
function configureWithdrawAssets(address[] calldata assets, bool[] calldata shouldWhitelist) external;
/**
* @notice Sets the settlement dispatcher address for a bin sponsor
* @dev Only callable by accounts with CASH_MODULE_CONTROLLER_ROLE
* @param binSponsor Bin sponsor for which the settlement dispatcher is updated
* @param dispatcher Address of the new settlement dispatcher for the bin sponsor
* @custom:throws InvalidInput if caller doesn't have the controller role
*/
function setSettlementDispatcher(BinSponsor binSponsor, address dispatcher) external;
/**
* @notice Sets the tier for one or more safes
* @dev Assigns tiers which determine cashback percentages
* @param safes Array of safe addresses to update
* @param tiers Array of tiers to assign to the corresponding safe addresses
* @custom:throws OnlyEtherFiWallet if caller doesn't have the wallet role
* @custom:throws ArrayLengthMismatch if arrays have different lengths
* @custom:throws OnlyEtherFiSafe if any address is not a valid EtherFi Safe
* @custom:throws AlreadyInSameTier if a safe is already in the specified tier
*/
function setSafeTier(address[] memory safes, SafeTiers[] memory tiers) external;
/**
* @notice Sets the time delays for withdrawals, spending limit changes, and mode changes
* @dev Only callable by accounts with CASH_MODULE_CONTROLLER_ROLE
* @param withdrawalDelay Delay in seconds before a withdrawal can be finalized
* @param spendLimitDelay Delay in seconds before spending limit changes take effect
* @param modeDelay Delay in seconds before a mode change takes effect
* @custom:throws OnlyCashModuleController if caller doesn't have the controller role
*/
function setDelays(uint64 withdrawalDelay, uint64 spendLimitDelay, uint64 modeDelay) external;
/**
* @notice Sets the operating mode for a safe
* @dev Switches between Debit and Credit modes with delay
* @param safe Address of the EtherFi Safe
* @param mode The target mode (Debit or Credit)
* @param signer Address of the safe admin signing the transaction
* @param signature Signature from the signer authorizing this mode change
* @custom:throws OnlyEtherFiSafe if the caller is not a valid EtherFi Safe
* @custom:throws OnlySafeAdmin if signer is not a safe admin
* @custom:throws ModeAlreadySet if the safe is already in the requested mode
* @custom:throws InvalidSignatures if signature verification fails
*/
function setMode(address safe, Mode mode, address signer, bytes calldata signature) external;
/**
* @notice Updates the spending limits for a safe
* @dev Can only be called by the safe itself with a valid admin signature
* @param safe Address of the EtherFi Safe
* @param dailyLimitInUsd New daily spending limit in USD
* @param monthlyLimitInUsd New monthly spending limit in USD
* @param signer Address of the safe admin signing the transaction
* @param signature Signature from the signer authorizing this update
* @custom:throws OnlyEtherFiSafe if the caller is not a valid EtherFi Safe
* @custom:throws OnlySafeAdmin if signer is not a safe admin
* @custom:throws InvalidSignatures if signature verification fails
*/
function updateSpendingLimit(address safe, uint256 dailyLimitInUsd, uint256 monthlyLimitInUsd, address signer, bytes calldata signature) external;
/**
* @notice Processes a spending transaction with multiple tokens
* @dev Only callable by EtherFi wallet for valid EtherFi Safe addresses
* @param safe Address of the EtherFi Safe
* @param txId Transaction identifier
* @param binSponsor Bin sponsor used for spending
* @param tokens Array of addresses of the tokens to spend
* @param amountsInUsd Array of amounts to spend in USD (must match tokens array length)
* @param cashbacks Struct of Cashback to be given
* @custom:throws TransactionAlreadyCleared if the transaction was already processed
* @custom:throws UnsupportedToken if any token is not supported
* @custom:throws AmountZero if any converted amount is zero
* @custom:throws ArrayLengthMismatch if token and amount arrays have different lengths
* @custom:throws OnlyOneTokenAllowedInCreditMode if multiple tokens are used in credit mode
* @custom:throws If spending would exceed limits or balances
*/
function spend(address safe, bytes32 txId, BinSponsor binSponsor, address[] calldata tokens, uint256[] calldata amountsInUsd, Cashback[] calldata cashbacks) external;
/**
* @notice Clears pending cashback for users
* @param users Addresses of users to clear the pending cashback for
* @param tokens Addresses of cashback tokens
*/
function clearPendingCashback(address[] calldata users, address[] calldata tokens) external;
/**
* @notice Repays borrowed tokens
* @dev Only callable by EtherFi wallet for valid EtherFi Safe addresses
* @param safe Address of the EtherFi Safe
* @param token Address of the token to repay
* @param amountInUsd Amount to repay in USD
* @custom:throws OnlyEtherFiWallet if caller doesn't have the wallet role
* @custom:throws OnlyEtherFiSafe if the safe is not a valid EtherFi Safe
* @custom:throws OnlyBorrowToken if token is not a valid borrow token
* @custom:throws AmountZero if the converted amount is zero
* @custom:throws InsufficientBalance if there is not enough balance for the operation
*/
function repay(address safe, address token, uint256 amountInUsd) external;
/**
* @notice Requests a withdrawal of tokens to a recipient
* @dev Creates a pending withdrawal request that can be processed after the delay period
* @dev Can only be done by the quorum of owners of the safe
* @param safe Address of the EtherFi Safe
* @param tokens Array of token addresses to withdraw
* @param amounts Array of token amounts to withdraw
* @param recipient Address to receive the withdrawn tokens
* @param signers Array of safe owner addresses signing the transaction
* @param signatures Array of signatures from the safe owners
* @custom:throws OnlyEtherFiSafe if the caller is not a valid EtherFi Safe
* @custom:throws InvalidSignatures if signature verification fails
* @custom:throws RecipientCannotBeAddressZero if recipient is the zero address
* @custom:throws ArrayLengthMismatch if arrays have different lengths
* @custom:throws InsufficientBalance if any token has insufficient balance
*/
function requestWithdrawal(address safe, address[] calldata tokens, uint256[] calldata amounts, address recipient, address[] calldata signers, bytes[] calldata signatures) external;
/**
* @notice Processes a pending withdrawal request after the delay period
* @dev Executes the token transfers and clears the request
* @param safe Address of the EtherFi Safe
* @custom:throws OnlyEtherFiSafe if the caller is not a valid EtherFi Safe
* @custom:throws CannotWithdrawYet if the withdrawal delay period hasn't passed
*/
function processWithdrawal(address safe) external;
/**
* @notice Prepares a safe for liquidation by canceling any pending withdrawals
* @dev Only callable by the DebtManager
* @param safe Address of the EtherFi Safe being liquidated
* @custom:throws OnlyDebtManager if called by any address other than the DebtManager
*/
function preLiquidate(address safe) external;
/**
* @notice Executes post-liquidation logic to transfer tokens to the liquidator
* @dev Only callable by the DebtManager after a successful liquidation
* @param safe Address of the EtherFi Safe being liquidated
* @param liquidator Address that will receive the liquidated tokens
* @param tokensToSend Array of token data with amounts to send to the liquidator
* @custom:throws OnlyDebtManager if called by any address other than the DebtManager
*/
function postLiquidate(address safe, address liquidator, IDebtManager.LiquidationTokenData[] memory tokensToSend) external;
/**
* @notice Returns the current nonce for a Safe
* @param safe The Safe address to query
* @return Current nonce value
* @dev Nonces are used to prevent signature replay attacks
*/
function getNonce(address safe) external view returns (uint256);
/**
* @notice Sets the new CashModuleSetters implementation address
* @dev Only callable by accounts with CASH_MODULE_CONTROLLER_ROLE
* @param newCashModuleSetters Address of the new CashModuleSetters implementation
* @custom:throws OnlyCashModuleController if caller doesn't have the controller role
* @custom:throws InvalidInput if newCashModuleSetters = address(0)
*/
function setCashModuleSettersAddress(address newCashModuleSetters) external;
/**
* @notice Fetched the safe tier
* @param safe Address of the safe
* @return SafeTiers Tier of the safe
*/
function getSafeTier(address safe) external view returns (SafeTiers);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
interface ILayerZeroTeller {
struct Asset {
bool allowDeposits;
bool allowWithdraws;
uint16 sharePremium;
}
function vault() external view returns (BoringVault);
function assetData(ERC20 asset) external view returns (Asset memory);
function deposit(ERC20 depositAsset, uint256 depositAmount, uint256 minimumMint) external payable returns (uint256 shares);
function bridge(uint96 shareAmount, address to, bytes calldata bridgeWildCard, ERC20 feeToken, uint256 maxFee) external payable;
function previewFee(uint96 shareAmount, address to, bytes calldata bridgeWildCard, ERC20 feeToken) external view returns (uint256 fee);
function accountant() external view returns (AccountantWithRateProviders);
}
interface BoringVault {}
interface AccountantWithRateProviders {
function getRate() external view returns (uint256 rate);
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/**
* @title IRoleRegistry
* @notice Interface for role-based access control management
* @dev Provides functions for managing and querying role assignments
*/
interface IRoleRegistry {
/**
* @notice Verifies if an account has pauser privileges
* @param account The address to check for pauser role
* @custom:throws Reverts if account is not an authorized pauser
*/
function onlyPauser(address account) external view;
/**
* @notice Verifies if an account has unpauser privileges
* @param account The address to check for unpauser role
* @custom:throws Reverts if account is not an authorized unpauser
*/
function onlyUnpauser(address account) external view;
/**
* @notice Checks if an account has any of the specified roles
* @dev Reverts if the account doesn't have at least one of the roles
* @param account The address to check roles for
* @param encodedRoles ABI encoded roles using abi.encode(ROLE_1, ROLE_2, ...)
* @custom:throws Reverts if account has none of the specified roles
*/
function checkRoles(address account, bytes memory encodedRoles) external view;
/**
* @notice Checks if an account has a specific role
* @dev Direct query for a single role status
* @param role The role identifier to check
* @param account The address to check the role for
* @return True if the account has the role, false otherwise
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @notice Grants a role to an account
* @dev Only callable by the contract owner
* @param role The role identifier to grant
* @param account The address to grant the role to
* @custom:access Restricted to contract owner
*/
function grantRole(bytes32 role, address account) external;
/**
* @notice Revokes a role from an account
* @dev Only callable by the contract owner
* @param role The role identifier to revoke
* @param account The address to revoke the role from
* @custom:access Restricted to contract owner
*/
function revokeRole(bytes32 role, address account) external;
/**
* @notice Retrieves all addresses that have a specific role
* @dev Wrapper around EnumerableRoles roleHolders function
* @param role The role identifier to query
* @return Array of addresses that have the specified role
*/
function roleHolders(bytes32 role) external view returns (address[] memory);
/**
* @notice Verifies if an account has upgrader privileges
* @dev Used for upgrade authorization checks
* @param account The address to check for upgrader role
* @custom:throws Reverts if account is not an authorized upgrader
*/
function onlyUpgrader(address account) external view;
/**
* @notice Returns the owner of the contract
* @return result Owner of the contract
*/
function owner() external view returns (address result);
/**
* @notice Generates a unique role identifier for safe administrators
* @dev Creates a unique bytes32 identifier by hashing the safe address with a role type
* @param safe The address of the safe for which to generate the admin role
* @return bytes32 A unique role identifier for the specified safe's admins
* @custom:throws InvalidInput if safe is a zero address
*/
function getSafeAdminRole(address safe) external pure returns (bytes32);
/**
* @notice Configures admin roles for a specific safe
* @dev Grants/revokes admin privileges to specified addresses for a particular safe
* @param accounts Array of admin addresses to configure
* @param shouldAdd Array indicating whether to add or remove each admin
* @custom:throws OnlyEtherFiSafe if called by any address other than a registered EtherFiSafe
* @custom:throws InvalidInput if the admins array is empty or contains a zero address
* @custom:throws ArrayLengthMismatch if the array lengths mismatch
*/
function configureSafeAdmins(address[] calldata accounts, bool[] calldata shouldAdd) external;
/**
* @notice Verifies if an account has safe admin privileges
* @param safe The address of the safe
* @param account The address to check for safe admin role
* @custom:throws OnlySafeAdmin if the account does not have the SafeAdmin role
*/
function onlySafeAdmin(address safe, address account) external view;
/**
* @notice Returns if an account has safe admin privileges
* @param safe The address of the safe
* @param account The address to check for safe admin role
* @return bool suggesting if the account has the safe admin role
*/
function isSafeAdmin(address safe, address account) external view returns (bool);
/**
* @notice Retrieves all addresses that have the safe admin role for a particular safe
* @param safe The address of the safe
* @return Array of addresses that have the safe admin role
*/
function getSafeAdmins(address safe) external view returns (address[] memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { IEtherFiDataProvider } from "../interfaces/IEtherFiDataProvider.sol";
import { IEtherFiSafe } from "../interfaces/IEtherFiSafe.sol";
import { SignatureUtils } from "../libraries/SignatureUtils.sol";
import { Constants } from "../utils/Constants.sol";
/**
* @title ModuleBase
* @author ether.fi
* @notice Base contract for implementing modules with admin functionality
* @dev Provides common functionality for modules including admin management and signature verification
* Uses ERC-7201 for namespace storage pattern
*/
contract ModuleBase is Constants {
using SignatureUtils for bytes32;
IEtherFiDataProvider public immutable etherFiDataProvider;
/// @notice Throws when the msg.sender is not an admin to the safe
error OnlySafeAdmin();
/// @notice Thrown when the input is invalid
error InvalidInput();
/// @notice Thrown when the signature verification fails
error InvalidSignature();
/// @notice Thrown when there is an array length mismatch
error ArrayLengthMismatch();
/// @notice Thrown when the caller is not an EtherFi Safe
error OnlyEtherFiSafe();
/// @notice Thrown when insufficient amount is available for use from the safe
error AmountNotAvailable();
/// @custom:storage-location erc7201:etherfi.storage.ModuleBaseStorage
struct ModuleBaseStorage {
/// @notice Mapping of Safe addresses to their nonces for replay protection
mapping(address safe => uint256 nonce) nonces;
}
// keccak256(abi.encode(uint256(keccak256("etherfi.storage.ModuleBaseStorage")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ModuleBaseStorageLocation = 0x9425b2e03e09da4c20ff7a465da264f7a02bf7079e1dbb47fce0436e1d206d00;
constructor(address _etherFiDataProvider) {
if (_etherFiDataProvider == address(0)) revert InvalidInput();
etherFiDataProvider = IEtherFiDataProvider(_etherFiDataProvider);
}
/**
* @dev Returns the storage struct from the specified storage slot
* @return $ Reference to the ModuleBaseStorage struct
*/
function _getModuleBaseStorage() internal pure returns (ModuleBaseStorage storage $) {
assembly {
$.slot := ModuleBaseStorageLocation
}
}
/**
* @notice Returns the current nonce for a Safe
* @param safe The Safe address to query
* @return Current nonce value
* @dev Nonces are used to prevent signature replay attacks
*/
function getNonce(address safe) public view returns (uint256) {
return _getModuleBaseStorage().nonces[safe];
}
/**
* @dev Uses and increments the nonce for a Safe
* @param safe The Safe address
* @return The nonce value before incrementing
*/
function _useNonce(address safe) internal returns (uint256) {
ModuleBaseStorage storage $ = _getModuleBaseStorage();
unchecked {
return $.nonces[safe]++;
}
}
/**
* @dev Verifies if a signature is valid and made by an admin of the safe
* @param digestHash The message hash that was signed
* @param signer The address that supposedly signed the message
* @param signature The signature to verify
* @custom:throws SignerIsNotAnAdmin If the signer is not an admin of the Safe
* @custom:throws InvalidSignature If the signature is invalid
*/
function _verifyAdminSig(bytes32 digestHash, address signer, bytes calldata signature) internal view {
if (!digestHash.isValidSignature(signer, signature)) revert InvalidSignature();
}
/**
* @dev Ensures that the caller is an admin for the specified Safe
* @param safe The Safe address to check admin status for
*/
modifier onlySafeAdmin(address safe, address account) {
if (!IEtherFiSafe(safe).isAdmin(account)) revert OnlySafeAdmin();
_;
}
/**
* @dev Ensures that the account is an instance of the deployed EtherfiSafe
* @param account The account address to check
*/
modifier onlyEtherFiSafe(address account) {
if (!etherFiDataProvider.isEtherFiSafe(account)) revert OnlyEtherFiSafe();
_;
}
/**
* @notice Sets up a new Safe's Module with initial configuration
* @dev Override this function to configure a module initially
* @param data The encoded initialization data
*/
function setupModule(bytes calldata data) external virtual { }
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { IEtherFiDataProvider } from "../interfaces/IEtherFiDataProvider.sol";
import { IEtherFiSafe } from "../interfaces/IEtherFiSafe.sol";
import { ICashModule } from "../interfaces/ICashModule.sol";
import { SignatureUtils } from "../libraries/SignatureUtils.sol";
import { Constants } from "../utils/Constants.sol";
/**
* @title ModuleCheckBalance
* @author ether.fi
* @notice Contract for checking available balance of a user's safe
*/
abstract contract ModuleCheckBalance is Constants {
using SignatureUtils for bytes32;
ICashModule public immutable cashModule;
/// @notice Thrown when insufficient amount is available for use from the safe
error InsufficientAvailableBalanceOnSafe();
constructor(address _etherFiDataProvider) {
cashModule = ICashModule(IEtherFiDataProvider(_etherFiDataProvider).getCashModule());
}
/**
* @notice Returns the available amount for an asset for a safe (balance - pendingWithdrawal)
* @param safe The Safe address to query
* @param asset Address of the asset
* @return Available amount (balance - pendingWithdrawal)
*/
function _getAvailableAmount(address safe, address asset) internal view returns (uint256) {
uint256 pendingWithdrawalAmount = cashModule.getPendingWithdrawalAmount(safe, asset);
uint256 balance;
if (asset == ETH) balance = safe.balance;
else balance = IERC20(asset).balanceOf(safe);
if (pendingWithdrawalAmount > balance) return 0;
return balance - pendingWithdrawalAmount;
}
/**
* @notice Checks if amount is available to use from the safe
* @param safe The Safe address to query
* @param asset Address of the asset
* @param amount Amount to check with
* @custom:throws InsufficientAvailableBalanceOnSafe if amount not available
*/
function _checkAmountAvailable(address safe, address asset, uint256 amount) internal view {
if (amount > _getAvailableAmount(safe, asset)) revert InsufficientAvailableBalanceOnSafe();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IBridgeModule {
/**
* @notice Cancels a bridge request by the cash module
* @dev This function is intended to be called by the cash module to cancel a bridge
* @param safe Address of the EtherFiSafe
*/
function cancelBridgeByCashModule(address safe) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 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 ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-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 ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guaratees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(buffer, add(0x20, offset)))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for managing enumerable sets in storage.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/EnumerableSetLib.sol)
///
/// @dev Note:
/// In many applications, the number of elements in an enumerable set is small.
/// This enumerable set implementation avoids storing the length and indices
/// for up to 3 elements. Once the length exceeds 3 for the first time, the length
/// and indices will be initialized. The amortized cost of adding elements is O(1).
///
/// The AddressSet implementation packs the length with the 0th entry.
///
/// All enumerable sets except Uint8Set use a pop and swap mechanism to remove elements.
/// This means that the iteration order of elements can change between element removals.
library EnumerableSetLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The index must be less than the length.
error IndexOutOfBounds();
/// @dev The value cannot be the zero sentinel.
error ValueIsZeroSentinel();
/// @dev Cannot accommodate a new unique value with the capacity.
error ExceedsCapacity();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev A sentinel value to denote the zero value in storage.
/// No elements can be equal to this value.
/// `uint72(bytes9(keccak256(bytes("_ZERO_SENTINEL"))))`.
uint256 private constant _ZERO_SENTINEL = 0xfbb67fda52d4bfb8bf;
/// @dev The storage layout is given by:
/// ```
/// mstore(0x04, _ENUMERABLE_ADDRESS_SET_SLOT_SEED)
/// mstore(0x00, set.slot)
/// let rootSlot := keccak256(0x00, 0x24)
/// mstore(0x20, rootSlot)
/// mstore(0x00, shr(96, shl(96, value)))
/// let positionSlot := keccak256(0x00, 0x40)
/// let valueSlot := add(rootSlot, sload(positionSlot))
/// let valueInStorage := shr(96, sload(valueSlot))
/// let lazyLength := shr(160, shl(160, sload(rootSlot)))
/// ```
uint256 private constant _ENUMERABLE_ADDRESS_SET_SLOT_SEED = 0x978aab92;
/// @dev The storage layout is given by:
/// ```
/// mstore(0x04, _ENUMERABLE_WORD_SET_SLOT_SEED)
/// mstore(0x00, set.slot)
/// let rootSlot := keccak256(0x00, 0x24)
/// mstore(0x20, rootSlot)
/// mstore(0x00, value)
/// let positionSlot := keccak256(0x00, 0x40)
/// let valueSlot := add(rootSlot, sload(positionSlot))
/// let valueInStorage := sload(valueSlot)
/// let lazyLength := sload(not(rootSlot))
/// ```
uint256 private constant _ENUMERABLE_WORD_SET_SLOT_SEED = 0x18fb5864;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev An enumerable address set in storage.
struct AddressSet {
uint256 _spacer;
}
/// @dev An enumerable bytes32 set in storage.
struct Bytes32Set {
uint256 _spacer;
}
/// @dev An enumerable uint256 set in storage.
struct Uint256Set {
uint256 _spacer;
}
/// @dev An enumerable int256 set in storage.
struct Int256Set {
uint256 _spacer;
}
/// @dev An enumerable uint8 set in storage. Useful for enums.
struct Uint8Set {
uint256 data;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GETTERS / SETTERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of elements in the set.
function length(AddressSet storage set) internal view returns (uint256 result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
let rootPacked := sload(rootSlot)
let n := shr(160, shl(160, rootPacked))
result := shr(1, n)
for {} iszero(or(iszero(shr(96, rootPacked)), n)) {} {
result := 1
if iszero(sload(add(rootSlot, result))) { break }
result := 2
if iszero(sload(add(rootSlot, result))) { break }
result := 3
break
}
}
}
/// @dev Returns the number of elements in the set.
function length(Bytes32Set storage set) internal view returns (uint256 result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
let n := sload(not(rootSlot))
result := shr(1, n)
for {} iszero(n) {} {
result := 0
if iszero(sload(add(rootSlot, result))) { break }
result := 1
if iszero(sload(add(rootSlot, result))) { break }
result := 2
if iszero(sload(add(rootSlot, result))) { break }
result := 3
break
}
}
}
/// @dev Returns the number of elements in the set.
function length(Uint256Set storage set) internal view returns (uint256 result) {
result = length(_toBytes32Set(set));
}
/// @dev Returns the number of elements in the set.
function length(Int256Set storage set) internal view returns (uint256 result) {
result = length(_toBytes32Set(set));
}
/// @dev Returns the number of elements in the set.
function length(Uint8Set storage set) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
for { let packed := sload(set.slot) } packed { result := add(1, result) } {
packed := xor(packed, and(packed, add(1, not(packed))))
}
}
}
/// @dev Returns whether `value` is in the set.
function contains(AddressSet storage set, address value) internal view returns (bool result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
value := shr(96, shl(96, value))
if eq(value, _ZERO_SENTINEL) {
mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
revert(0x1c, 0x04)
}
if iszero(value) { value := _ZERO_SENTINEL }
let rootPacked := sload(rootSlot)
for {} 1 {} {
if iszero(shr(160, shl(160, rootPacked))) {
result := 1
if eq(shr(96, rootPacked), value) { break }
if eq(shr(96, sload(add(rootSlot, 1))), value) { break }
if eq(shr(96, sload(add(rootSlot, 2))), value) { break }
result := 0
break
}
mstore(0x20, rootSlot)
mstore(0x00, value)
result := iszero(iszero(sload(keccak256(0x00, 0x40))))
break
}
}
}
/// @dev Returns whether `value` is in the set.
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
if eq(value, _ZERO_SENTINEL) {
mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
revert(0x1c, 0x04)
}
if iszero(value) { value := _ZERO_SENTINEL }
for {} 1 {} {
if iszero(sload(not(rootSlot))) {
result := 1
if eq(sload(rootSlot), value) { break }
if eq(sload(add(rootSlot, 1)), value) { break }
if eq(sload(add(rootSlot, 2)), value) { break }
result := 0
break
}
mstore(0x20, rootSlot)
mstore(0x00, value)
result := iszero(iszero(sload(keccak256(0x00, 0x40))))
break
}
}
}
/// @dev Returns whether `value` is in the set.
function contains(Uint256Set storage set, uint256 value) internal view returns (bool result) {
result = contains(_toBytes32Set(set), bytes32(value));
}
/// @dev Returns whether `value` is in the set.
function contains(Int256Set storage set, int256 value) internal view returns (bool result) {
result = contains(_toBytes32Set(set), bytes32(uint256(value)));
}
/// @dev Returns whether `value` is in the set.
function contains(Uint8Set storage set, uint8 value) internal view returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := and(1, shr(and(0xff, value), sload(set.slot)))
}
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
function add(AddressSet storage set, address value) internal returns (bool result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
value := shr(96, shl(96, value))
if eq(value, _ZERO_SENTINEL) {
mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
revert(0x1c, 0x04)
}
if iszero(value) { value := _ZERO_SENTINEL }
let rootPacked := sload(rootSlot)
for { let n := shr(160, shl(160, rootPacked)) } 1 {} {
mstore(0x20, rootSlot)
if iszero(n) {
let v0 := shr(96, rootPacked)
if iszero(v0) {
sstore(rootSlot, shl(96, value))
result := 1
break
}
if eq(v0, value) { break }
let v1 := shr(96, sload(add(rootSlot, 1)))
if iszero(v1) {
sstore(add(rootSlot, 1), shl(96, value))
result := 1
break
}
if eq(v1, value) { break }
let v2 := shr(96, sload(add(rootSlot, 2)))
if iszero(v2) {
sstore(add(rootSlot, 2), shl(96, value))
result := 1
break
}
if eq(v2, value) { break }
mstore(0x00, v0)
sstore(keccak256(0x00, 0x40), 1)
mstore(0x00, v1)
sstore(keccak256(0x00, 0x40), 2)
mstore(0x00, v2)
sstore(keccak256(0x00, 0x40), 3)
rootPacked := or(rootPacked, 7)
n := 7
}
mstore(0x00, value)
let p := keccak256(0x00, 0x40)
if iszero(sload(p)) {
n := shr(1, n)
result := 1
sstore(p, add(1, n))
if iszero(n) {
sstore(rootSlot, or(3, shl(96, value)))
break
}
sstore(add(rootSlot, n), shl(96, value))
sstore(rootSlot, add(2, rootPacked))
break
}
break
}
}
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
function add(Bytes32Set storage set, bytes32 value) internal returns (bool result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
if eq(value, _ZERO_SENTINEL) {
mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
revert(0x1c, 0x04)
}
if iszero(value) { value := _ZERO_SENTINEL }
for { let n := sload(not(rootSlot)) } 1 {} {
mstore(0x20, rootSlot)
if iszero(n) {
let v0 := sload(rootSlot)
if iszero(v0) {
sstore(rootSlot, value)
result := 1
break
}
if eq(v0, value) { break }
let v1 := sload(add(rootSlot, 1))
if iszero(v1) {
sstore(add(rootSlot, 1), value)
result := 1
break
}
if eq(v1, value) { break }
let v2 := sload(add(rootSlot, 2))
if iszero(v2) {
sstore(add(rootSlot, 2), value)
result := 1
break
}
if eq(v2, value) { break }
mstore(0x00, v0)
sstore(keccak256(0x00, 0x40), 1)
mstore(0x00, v1)
sstore(keccak256(0x00, 0x40), 2)
mstore(0x00, v2)
sstore(keccak256(0x00, 0x40), 3)
n := 7
}
mstore(0x00, value)
let p := keccak256(0x00, 0x40)
if iszero(sload(p)) {
n := shr(1, n)
sstore(add(rootSlot, n), value)
sstore(p, add(1, n))
sstore(not(rootSlot), or(1, shl(1, add(1, n))))
result := 1
break
}
break
}
}
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
function add(Uint256Set storage set, uint256 value) internal returns (bool result) {
result = add(_toBytes32Set(set), bytes32(value));
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
function add(Int256Set storage set, int256 value) internal returns (bool result) {
result = add(_toBytes32Set(set), bytes32(uint256(value)));
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
function add(Uint8Set storage set, uint8 value) internal returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(set.slot)
let mask := shl(and(0xff, value), 1)
sstore(set.slot, or(result, mask))
result := iszero(and(result, mask))
}
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
/// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
function add(AddressSet storage set, address value, uint256 cap)
internal
returns (bool result)
{
if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
/// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
function add(Bytes32Set storage set, bytes32 value, uint256 cap)
internal
returns (bool result)
{
if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
/// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
function add(Uint256Set storage set, uint256 value, uint256 cap)
internal
returns (bool result)
{
if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
/// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
function add(Int256Set storage set, int256 value, uint256 cap) internal returns (bool result) {
if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
}
/// @dev Adds `value` to the set. Returns whether `value` was not in the set.
/// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
function add(Uint8Set storage set, uint8 value, uint256 cap) internal returns (bool result) {
if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
}
/// @dev Removes `value` from the set. Returns whether `value` was in the set.
function remove(AddressSet storage set, address value) internal returns (bool result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
value := shr(96, shl(96, value))
if eq(value, _ZERO_SENTINEL) {
mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
revert(0x1c, 0x04)
}
if iszero(value) { value := _ZERO_SENTINEL }
let rootPacked := sload(rootSlot)
for { let n := shr(160, shl(160, rootPacked)) } 1 {} {
if iszero(n) {
result := 1
if eq(shr(96, rootPacked), value) {
sstore(rootSlot, sload(add(rootSlot, 1)))
sstore(add(rootSlot, 1), sload(add(rootSlot, 2)))
sstore(add(rootSlot, 2), 0)
break
}
if eq(shr(96, sload(add(rootSlot, 1))), value) {
sstore(add(rootSlot, 1), sload(add(rootSlot, 2)))
sstore(add(rootSlot, 2), 0)
break
}
if eq(shr(96, sload(add(rootSlot, 2))), value) {
sstore(add(rootSlot, 2), 0)
break
}
result := 0
break
}
mstore(0x20, rootSlot)
mstore(0x00, value)
let p := keccak256(0x00, 0x40)
let position := sload(p)
if iszero(position) { break }
n := sub(shr(1, n), 1)
if iszero(eq(sub(position, 1), n)) {
let lastValue := shr(96, sload(add(rootSlot, n)))
sstore(add(rootSlot, sub(position, 1)), shl(96, lastValue))
mstore(0x00, lastValue)
sstore(keccak256(0x00, 0x40), position)
}
sstore(rootSlot, or(shl(96, shr(96, sload(rootSlot))), or(shl(1, n), 1)))
sstore(p, 0)
result := 1
break
}
}
}
/// @dev Removes `value` from the set. Returns whether `value` was in the set.
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
if eq(value, _ZERO_SENTINEL) {
mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
revert(0x1c, 0x04)
}
if iszero(value) { value := _ZERO_SENTINEL }
for { let n := sload(not(rootSlot)) } 1 {} {
if iszero(n) {
result := 1
if eq(sload(rootSlot), value) {
sstore(rootSlot, sload(add(rootSlot, 1)))
sstore(add(rootSlot, 1), sload(add(rootSlot, 2)))
sstore(add(rootSlot, 2), 0)
break
}
if eq(sload(add(rootSlot, 1)), value) {
sstore(add(rootSlot, 1), sload(add(rootSlot, 2)))
sstore(add(rootSlot, 2), 0)
break
}
if eq(sload(add(rootSlot, 2)), value) {
sstore(add(rootSlot, 2), 0)
break
}
result := 0
break
}
mstore(0x20, rootSlot)
mstore(0x00, value)
let p := keccak256(0x00, 0x40)
let position := sload(p)
if iszero(position) { break }
n := sub(shr(1, n), 1)
if iszero(eq(sub(position, 1), n)) {
let lastValue := sload(add(rootSlot, n))
sstore(add(rootSlot, sub(position, 1)), lastValue)
mstore(0x00, lastValue)
sstore(keccak256(0x00, 0x40), position)
}
sstore(not(rootSlot), or(shl(1, n), 1))
sstore(p, 0)
result := 1
break
}
}
}
/// @dev Removes `value` from the set. Returns whether `value` was in the set.
function remove(Uint256Set storage set, uint256 value) internal returns (bool result) {
result = remove(_toBytes32Set(set), bytes32(value));
}
/// @dev Removes `value` from the set. Returns whether `value` was in the set.
function remove(Int256Set storage set, int256 value) internal returns (bool result) {
result = remove(_toBytes32Set(set), bytes32(uint256(value)));
}
/// @dev Removes `value` from the set. Returns whether `value` was in the set.
function remove(Uint8Set storage set, uint8 value) internal returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(set.slot)
let mask := shl(and(0xff, value), 1)
sstore(set.slot, and(result, not(mask)))
result := iszero(iszero(and(result, mask)))
}
}
/// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
function update(AddressSet storage set, address value, bool isAdd, uint256 cap)
internal
returns (bool)
{
return isAdd ? add(set, value, cap) : remove(set, value);
}
/// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
function update(Bytes32Set storage set, bytes32 value, bool isAdd, uint256 cap)
internal
returns (bool)
{
return isAdd ? add(set, value, cap) : remove(set, value);
}
/// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
function update(Uint256Set storage set, uint256 value, bool isAdd, uint256 cap)
internal
returns (bool)
{
return isAdd ? add(set, value, cap) : remove(set, value);
}
/// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
function update(Int256Set storage set, int256 value, bool isAdd, uint256 cap)
internal
returns (bool)
{
return isAdd ? add(set, value, cap) : remove(set, value);
}
/// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
function update(Uint8Set storage set, uint8 value, bool isAdd, uint256 cap)
internal
returns (bool)
{
return isAdd ? add(set, value, cap) : remove(set, value);
}
/// @dev Returns all of the values in the set.
/// Note: This can consume more gas than the block gas limit for large sets.
function values(AddressSet storage set) internal view returns (address[] memory result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
let zs := _ZERO_SENTINEL
let rootPacked := sload(rootSlot)
let n := shr(160, shl(160, rootPacked))
result := mload(0x40)
let o := add(0x20, result)
let v := shr(96, rootPacked)
mstore(o, mul(v, iszero(eq(v, zs))))
for {} 1 {} {
if iszero(n) {
if v {
n := 1
v := shr(96, sload(add(rootSlot, n)))
if v {
n := 2
mstore(add(o, 0x20), mul(v, iszero(eq(v, zs))))
v := shr(96, sload(add(rootSlot, n)))
if v {
n := 3
mstore(add(o, 0x40), mul(v, iszero(eq(v, zs))))
}
}
}
break
}
n := shr(1, n)
for { let i := 1 } lt(i, n) { i := add(i, 1) } {
v := shr(96, sload(add(rootSlot, i)))
mstore(add(o, shl(5, i)), mul(v, iszero(eq(v, zs))))
}
break
}
mstore(result, n)
mstore(0x40, add(o, shl(5, n)))
}
}
/// @dev Returns all of the values in the set.
/// Note: This can consume more gas than the block gas limit for large sets.
function values(Bytes32Set storage set) internal view returns (bytes32[] memory result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
let zs := _ZERO_SENTINEL
let n := sload(not(rootSlot))
result := mload(0x40)
let o := add(0x20, result)
for {} 1 {} {
if iszero(n) {
let v := sload(rootSlot)
if v {
n := 1
mstore(o, mul(v, iszero(eq(v, zs))))
v := sload(add(rootSlot, n))
if v {
n := 2
mstore(add(o, 0x20), mul(v, iszero(eq(v, zs))))
v := sload(add(rootSlot, n))
if v {
n := 3
mstore(add(o, 0x40), mul(v, iszero(eq(v, zs))))
}
}
}
break
}
n := shr(1, n)
for { let i := 0 } lt(i, n) { i := add(i, 1) } {
let v := sload(add(rootSlot, i))
mstore(add(o, shl(5, i)), mul(v, iszero(eq(v, zs))))
}
break
}
mstore(result, n)
mstore(0x40, add(o, shl(5, n)))
}
}
/// @dev Returns all of the values in the set.
/// Note: This can consume more gas than the block gas limit for large sets.
function values(Uint256Set storage set) internal view returns (uint256[] memory result) {
result = _toUints(values(_toBytes32Set(set)));
}
/// @dev Returns all of the values in the set.
/// Note: This can consume more gas than the block gas limit for large sets.
function values(Int256Set storage set) internal view returns (int256[] memory result) {
result = _toInts(values(_toBytes32Set(set)));
}
/// @dev Returns all of the values in the set.
function values(Uint8Set storage set) internal view returns (uint8[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let ptr := add(result, 0x20)
let o := 0
for { let packed := sload(set.slot) } packed {} {
if iszero(and(packed, 0xffff)) {
o := add(o, 16)
packed := shr(16, packed)
continue
}
mstore(ptr, o)
ptr := add(ptr, shl(5, and(packed, 1)))
o := add(o, 1)
packed := shr(1, packed)
}
mstore(result, shr(5, sub(ptr, add(result, 0x20))))
mstore(0x40, ptr)
}
}
/// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
function at(AddressSet storage set, uint256 i) internal view returns (address result) {
bytes32 rootSlot = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
result := shr(96, sload(add(rootSlot, i)))
result := mul(result, iszero(eq(result, _ZERO_SENTINEL)))
}
if (i >= length(set)) revert IndexOutOfBounds();
}
/// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
function at(Bytes32Set storage set, uint256 i) internal view returns (bytes32 result) {
result = _rootSlot(set);
/// @solidity memory-safe-assembly
assembly {
result := sload(add(result, i))
result := mul(result, iszero(eq(result, _ZERO_SENTINEL)))
}
if (i >= length(set)) revert IndexOutOfBounds();
}
/// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
function at(Uint256Set storage set, uint256 i) internal view returns (uint256 result) {
result = uint256(at(_toBytes32Set(set), i));
}
/// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
function at(Int256Set storage set, uint256 i) internal view returns (int256 result) {
result = int256(uint256(at(_toBytes32Set(set), i)));
}
/// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
function at(Uint8Set storage set, uint256 i) internal view returns (uint8 result) {
/// @solidity memory-safe-assembly
assembly {
let packed := sload(set.slot)
for {} 1 {
mstore(0x00, 0x4e23d035) // `IndexOutOfBounds()`.
revert(0x1c, 0x04)
} {
if iszero(lt(i, 256)) { continue }
for { let j := 0 } iszero(eq(i, j)) {} {
packed := xor(packed, and(packed, add(1, not(packed))))
j := add(j, 1)
}
if iszero(packed) { continue }
break
}
// Find first set subroutine, optimized for smaller bytecode size.
let x := and(packed, add(1, not(packed)))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
result := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the root slot.
function _rootSlot(AddressSet storage s) private pure returns (bytes32 r) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x04, _ENUMERABLE_ADDRESS_SET_SLOT_SEED)
mstore(0x00, s.slot)
r := keccak256(0x00, 0x24)
}
}
/// @dev Returns the root slot.
function _rootSlot(Bytes32Set storage s) private pure returns (bytes32 r) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x04, _ENUMERABLE_WORD_SET_SLOT_SEED)
mstore(0x00, s.slot)
r := keccak256(0x00, 0x24)
}
}
/// @dev Casts to a Bytes32Set.
function _toBytes32Set(Uint256Set storage s) private pure returns (Bytes32Set storage c) {
/// @solidity memory-safe-assembly
assembly {
c.slot := s.slot
}
}
/// @dev Casts to a Bytes32Set.
function _toBytes32Set(Int256Set storage s) private pure returns (Bytes32Set storage c) {
/// @solidity memory-safe-assembly
assembly {
c.slot := s.slot
}
}
/// @dev Casts to a uint256 array.
function _toUints(bytes32[] memory a) private pure returns (uint256[] memory c) {
/// @solidity memory-safe-assembly
assembly {
c := a
}
}
/// @dev Casts to a int256 array.
function _toInts(bytes32[] memory a) private pure returns (int256[] memory c) {
/// @solidity memory-safe-assembly
assembly {
c := a
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { IEtherFiDataProvider } from "./IEtherFiDataProvider.sol";
import { BinSponsor } from "./ICashModule.sol";
interface IDebtManager {
struct BorrowTokenConfigData {
uint64 borrowApy;
uint128 minShares;
}
struct BorrowTokenConfig {
uint256 interestIndexSnapshot;
uint256 totalBorrowingAmount;
uint256 totalSharesOfBorrowTokens;
uint64 lastUpdateTimestamp;
uint64 borrowApy;
uint128 minShares;
}
struct CollateralTokenConfig {
uint80 ltv;
uint80 liquidationThreshold;
uint96 liquidationBonus;
}
struct TokenData {
address token;
uint256 amount;
}
struct LiquidationTokenData {
address token;
uint256 amount;
uint256 liquidationBonus;
}
event Supplied(address indexed sender, address indexed user, address indexed token, uint256 amount);
event Borrowed(address indexed user, address indexed token, uint256 amount);
event Repaid(address indexed user, address indexed payer, address indexed token, uint256 amount);
event Liquidated(address indexed liquidator, address indexed user, address indexed debtTokenToLiquidate, LiquidationTokenData[] userCollateralLiquidated, uint256 beforeDebtAmount, uint256 debtAmountLiquidated);
event LiquidationThresholdUpdated(uint256 oldThreshold, uint256 newThreshold);
event CollateralTokenAdded(address token);
event CollateralTokenRemoved(address token);
event BorrowTokenAdded(address token);
event BorrowTokenRemoved(address token);
event BorrowApySet(address indexed token, uint256 oldApy, uint256 newApy);
event MinSharesOfBorrowTokenSet(address indexed token, uint128 oldMinShares, uint128 newMinShares);
event UserInterestAdded(address indexed user, uint256 borrowingAmtBeforeInterest, uint256 borrowingAmtAfterInterest);
event TotalBorrowingUpdated(address indexed borrowToken, uint256 totalBorrowingAmtBeforeInterest, uint256 totalBorrowingAmtAfterInterest);
event BorrowTokenConfigSet(address indexed token, BorrowTokenConfig config);
event CollateralTokenConfigSet(address indexed collateralToken, CollateralTokenConfig oldConfig, CollateralTokenConfig newConfig);
event WithdrawBorrowToken(address indexed withdrawer, address indexed borrowToken, uint256 amount);
event InterestIndexUpdated(address indexed borrowToken, uint256 oldIndex, uint256 newIndex);
error CollateralPreferenceIsEmpty();
error UnsupportedCollateralToken();
error UnsupportedRepayToken();
error UnsupportedBorrowToken();
error InsufficientCollateral();
error InsufficientCollateralToRepay();
error InsufficientLiquidity();
error CannotLiquidateYet();
error ZeroCollateralValue();
error OnlyUserCanRepayWithCollateral();
error InvalidValue();
error AlreadyCollateralToken();
error AlreadyBorrowToken();
error NotACollateralToken();
error NoCollateralTokenLeft();
error NotABorrowToken();
error NoBorrowTokenLeft();
error ArrayLengthMismatch();
error TotalCollateralAmountNotZero();
error InsufficientLiquidityPleaseTryAgainLater();
error LiquidAmountLesserThanRequired();
error ZeroTotalBorrowTokens();
error InsufficientBorrowShares();
error UserStillLiquidatable();
error TotalBorrowingsForUserNotZero();
error BorrowTokenConfigAlreadySet();
error AccountUnhealthy();
error BorrowTokenStillInTheSystem();
error RepaymentAmountIsZero();
error LiquidatableAmountIsZero();
error LtvCannotBeGreaterThanLiquidationThreshold();
error OraclePriceZero();
error BorrowAmountZero();
error SharesCannotBeZero();
error SharesCannotBeLessThanMinShares();
error SupplyCapBreached();
error OnlyEtherFiSafe();
error EtherFiSafeCannotSupplyDebtTokens();
error BorrowTokenCannotBeRemovedFromCollateral();
/**
* @notice Function to fetch the admin role
* @return DEBT_MANAGER_ADMIN_ROLE
*/
function DEBT_MANAGER_ADMIN_ROLE() external view returns (bytes32);
/**
* @notice Returns the max borrow apy
* @return Max borrow APY
*/
function MAX_BORROW_APY() external view returns (uint64);
/**
* @notice Returns the address of DebtManagerAdmin implementation
* @return address DebtManagerAdmin implmentaion
*/
function getDebtManagerAdmin() external view returns (address);
/**
* @notice Returns an instance of the EtherFiDataProvider
* @return EtherFiDataProvider instance
*/
function etherFiDataProvider() external view returns (IEtherFiDataProvider);
/**
* @notice Function to fetch the address of the Cash Data Provider.
* @return Cash Data Provider address
*/
function cashDataProvider() external view returns (address);
/**
* @notice Function to fetch the debt interest index snapshot.
* @param borrowToken Address of the borrow token.
* @return debt interest index snapshot
*/
function debtInterestIndexSnapshot(address borrowToken) external view returns (uint256);
/**
* @notice Function to fetch the borrow APY per second with 18 decimals.
* @param borrowToken Address of the borrow token.
* @return Borrow APY per second. Eg: 0.0001% -> 0.0001e18
*/
function borrowApyPerSecond(address borrowToken) external view returns (uint64);
/**
* @notice Function to fetch the min shares of borrow token that can be minted by a supplier.
* @param borrowToken Address of the borrow token.
* @return minShares
*/
function borrowTokenMinShares(address borrowToken) external view returns (uint128);
/**
* @notice Function to fetch the array of collateral tokens.
* @return Array of collateral tokens.
*/
function getCollateralTokens() external view returns (address[] memory);
/**
* @notice Function to fetch the array of borrow tokens.
* @return Array of borrow tokens.
*/
function getBorrowTokens() external view returns (address[] memory);
/**
* @notice Function to check whether a token is a collateral token.
* @return Boolean value suggesting if token is a collateral token.
*/
function isCollateralToken(address token) external view returns (bool);
/**
* @notice Function to check whether a token is a borrow token.
* @return Boolean value suggesting if token is a borrow token.
*/
function isBorrowToken(address token) external view returns (bool);
/**
* @notice Function to add support for a new collateral token.
* @dev Can only be called by an address with the DEBT_MANAGER_ADMIN_ROLE.
* @param token Address of the token to be supported as collateral.
* @param config Collateral token config.
*/
function supportCollateralToken(address token, CollateralTokenConfig memory config) external;
/**
* @notice Function to set the borrow APY per second for a borrow token.
* @dev Can only be called by an address with the DEBT_MANAGER_ADMIN_ROLE.
* @param token Address of the borrow token.
* @param apy Borrow APY per seconds with 18 decimals.
*/
function setBorrowApy(address token, uint64 apy) external;
/**
* @notice Function to set min borrow token shares to mint.
* @notice Implemented to prevent inflation attacks.
* @param token Address of the borrow token.
* @param shares Min shares of that borrow token to mint.
*/
function setMinBorrowTokenShares(address token, uint128 shares) external;
/**
* @notice Function to set the collateral token config.
* @param __collateralToken Address of the collateral token.
* @param __config Collateral token config.
*/
function setCollateralTokenConfig(address __collateralToken, CollateralTokenConfig memory __config) external;
/**
* @notice Function to remove support for a collateral token.
* @dev Can only be called by an address with the DEBT_MANAGER_ADMIN_ROLE.
* @param token Address of the token to be unsupported as collateral.
*/
function unsupportCollateralToken(address token) external;
/**
* @notice Function to add support for a new borrow token.
* @dev Can only be called by an address with the DEBT_MANAGER_ADMIN_ROLE.
* @param token Address of the token to be supported as borrow.
* @param borrowApy Borrow APY per second in 18 decimals.
*/
function supportBorrowToken(address token, uint64 borrowApy, uint128 minBorrowTokenShares) external;
/**
* @notice Function to remove support for a borrow token.
* @dev Can only be called by an address with the DEBT_MANAGER_ADMIN_ROLE.
* @param token Address of the token to be unsupported as borrow.
*/
function unsupportBorrowToken(address token) external;
/**
* @notice Function to ensure that the debt position of the user safe is healthy
* @param user Address of the user safe
*/
function ensureHealth(address user) external view;
/**
* @notice Function to supply borrow tokens to the debt manager.
* @param user Address of the user to register for supply.
* @param borrowToken Address of the borrow token to supply.
* @param amount Amount of the borrow token to supply.
*/
function supply(address user, address borrowToken, uint256 amount) external;
/**
* @notice Function to withdraw the borrow tokens.
* @param borrowToken Address of the borrow token.
* @param amount Amount of the borrow token to withdraw.
*/
function withdrawBorrowToken(address borrowToken, uint256 amount) external;
/**
* @notice Function for users to borrow funds for payment using the deposited collateral.
* @notice Borrowed tokens are transferred to the `etherFiCashSafe`
* @param binSponsor Bin sponsor used to spend.
* @param token Address of the token to borrow.
* @param amount Amount of the token to borrow.
*/
function borrow(BinSponsor binSponsor, address token, uint256 amount) external;
/**
* @notice Function for users to repay the borrowed funds back to the debt manager.
* @param user Address of the user safe for whom the payment is made.
* @param token Address of the token in which repayment is done.
* @param amount Amount of tokens to be repaid.
*/
function repay(address user, address token, uint256 amount) external;
// https://docs.aave.com/faq/liquidations
/**
* @notice Liquidate the user's debt by repaying the partial/entire debt using the collateral.
* @notice If user's 50% debt is repaid and user is healthy, then only 50% will be repaid. Otherwise entire debt is repaid.
* @dev do we need to add penalty?
* @param user Address of the user to liquidate.
* @param borrowToken Borrow token address to liquidate.
* @param collateralTokensPreference Preference of order of collateral tokens to liquidate the user for.
*/
function liquidate(address user, address borrowToken, address[] memory collateralTokensPreference) external;
/**
* @notice Function to determine if a user is liquidatable.
* @param user Address of the user.
* @return isLiquidatable boolean value.
*/
function liquidatable(address user) external view returns (bool isLiquidatable);
/**
* @notice Function to fetch the collateral amount for the user.
* @param user Address of the user.
* @return Array of TokenData struct, total collateral amount in usd.
*/
function collateralOf(address user) external view returns (TokenData[] memory, uint256);
/**
* @notice Function to fetch the borrowing amount of the user for a borrow token.
* @param user Address of the user.
* @param borrowToken Address of the borrow token.
* @return Borrow amount with interest.
*/
function borrowingOf(address user, address borrowToken) external view returns (uint256);
/**
* @notice Function to fetch the borrowing amount of the user for a all the borrow tokens.
* @param user Address of the user.
* @return Array of TokenData struct, total borrow amount in usd.
*/
function borrowingOf(address user) external view returns (TokenData[] memory, uint256);
/**
* @notice Function to fetch the max borrow amount for ltv or liquidation purpose.
* @notice Calculates user's total collateral amount in USD and finds max borrowable amount using liquidation threshold.
* @param user Address of the user.
* @param forLtv For ltv, pass true and for liquidation, pass false.
* @return Max borrow amount for liquidation purpose.
*/
function getMaxBorrowAmount(address user, bool forLtv) external view returns (uint256);
/**
* @notice Function to fetch the max borrow and total current borrowings
* @param user Address of the user safe
* @param tokenAmounts Token amounts of collateral
* @return Total max borrow for that user
* @return Current total borrowings of the user
*/
function getBorrowingPowerAndTotalBorrowing(address user, TokenData[] memory tokenAmounts) external view returns (uint256, uint256);
/**
* @notice Function to determine the current borrowable amount in USD for a user.
* @param user Address of the user.
* @return Current borrowable amount for the user.
*/
function remainingBorrowingCapacityInUSD(address user) external view returns (uint256);
/**
* @notice Function to get the withdrawable amount of borrow tokens for a supplier.
* @param supplier Address of the supplier.
* @param borrowToken Address of the borrow token.
* @return Amount of borrow tokens the supplier can withdraw.
*/
function supplierBalance(address supplier, address borrowToken) external view returns (uint256);
/**
* @notice Function to get the withdrawable amount of borrow tokens for a supplier.
* @param supplier Address of the supplier.
* @return Array of borrow tokens addresses and respective amounts.
* @return Total amount in USD.
*/
function supplierBalance(address supplier) external view returns (TokenData[] memory, uint256);
/**
* @notice Function to fetch the total supplies for a borrow token.
* @param borrowToken Address of the borrow token.
* @return Total amount supplied.
*/
function totalSupplies(address borrowToken) external view returns (uint256);
/**
* @notice Function to fetch the total supplies for each borrow token.
* @return Total amount supplied for each borrow token.
* @return Total amount supplied in USD combined.
*/
function totalSupplies() external view returns (TokenData[] memory, uint256);
/**
* @notice Function to convert collateral token amount to equivalent USD amount.
* @param collateralToken Address of collateral to convert.
* @param collateralAmount Amount of collateral token to convert.
* @return Equivalent USD amount.
*/
function convertCollateralTokenToUsd(address collateralToken, uint256 collateralAmount) external view returns (uint256);
/**
* @notice Function to convert usd amount to collateral token amount.
* @param collateralToken Address of the collateral token.
* @param debtUsdAmount Amount of USD for borrowing.
* @return Amount of collateral required.
*/
function convertUsdToCollateralToken(address collateralToken, uint256 debtUsdAmount) external view returns (uint256);
/**
* @notice Function to fetch the value of collateral deposited by the user in USD.
* @param user Address of the user.
* @return Total collateral value in USD for the user.
*/
function getCollateralValueInUsd(address user) external view returns (uint256);
/**
* @notice Function to fetch the user collateral for a particular token.
* @param user Address of the user.
* @param token Address of the token.
* @return Amount of collateral in tokens.
* @return Amount of collateral in USD.
*/
function getUserCollateralForToken(address user, address token) external view returns (uint256, uint256);
/**
* @notice Function to fetch the total borrowing amount for a token from this contract.
* @param borrowToken Address of the borrow token.
* @return Total borrowing amount in debt token with 6 decimals.
*/
function totalBorrowingAmount(address borrowToken) external view returns (uint256);
/**
* @notice Function to fetch the total borrowing amounts from this contract.
* @return Array of borrow tokens with respective amount in USD.
* @return Total borrowing amount in USD.
*/
function totalBorrowingAmounts() external view returns (TokenData[] memory, uint256);
/**
* @notice Function to fetch the borrow token config.
* @param borrowToken Address of the borrow token.
* @return BorrowTokenConfig struct.
*/
function borrowTokenConfig(address borrowToken) external view returns (BorrowTokenConfig memory);
/**
* @notice Function to fetch the collateral token config.
* @param collateralToken Address of the collateral token.
* @return CollateralTokenConfig.
*/
function collateralTokenConfig(address collateralToken) external view returns (CollateralTokenConfig memory);
/**
* @notice Function to fetch the current state of collaterals and borrowings.
* @return borrowings Array of borrowings in tuple(address token, uint256 amount) format.
* @return totalBorrowingsInUsd Total borrowing value in USD.
* @return totalLiquidStableAmounts Total liquid stable amounts in tuple(address token, uint256 amount) format.
*/
function getCurrentState() external view returns (TokenData[] memory borrowings, uint256 totalBorrowingsInUsd, TokenData[] memory totalLiquidStableAmounts);
/**
* @notice Function to fetch the current state of a user.
* @return totalCollaterals Array of collaterals in tuple(address token, uint256 amount) format.
* @return totalCollateralInUsd Total collateral value in USD.
* @return borrowings Array of borrowings in tuple(address token, uint256 amount) format.
* @return totalBorrowings Total borrowing value in USD.
*/
function getUserCurrentState(address user) external view returns (TokenData[] memory totalCollaterals, uint256 totalCollateralInUsd, TokenData[] memory borrowings, uint256 totalBorrowings);
/**
* @notice Sets a new DebtManagerAdmin implementation
* @dev Can only be called by an address with the DEBT_MANAGER_ADMIN_ROLE.
* @param newImpl Address of the new DebtManagerAdmin implementation
*/
function setAdminImpl(address newImpl) external;
/**
* @notice Calculates the current interest index for a borrow token
* @dev Computes accrued interest based on time elapsed since last update
* @param borrowToken Address of the borrow token
* @return The current interest index including all accrued interest
*/
function getCurrentIndex(address borrowToken) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { IRoleRegistry } from "./IRoleRegistry.sol";
/**
* @title IEtherFiDataProvider
* @author ether.fi
* @notice Interface for the EtherFiDataProvider contract that manages important data for ether.fi
*/
interface IEtherFiDataProvider {
/**
* @notice Configures multiple modules' whitelist status
* @dev Only callable by addresses with ADMIN_ROLE
* @param modules Array of module addresses to configure
* @param shouldWhitelist Array of boolean values indicating whether each module should be whitelisted
*/
function configureModules(address[] calldata modules, bool[] calldata shouldWhitelist) external;
/**
* @notice Updates the hook address
* @dev Only callable by addresses with ADMIN_ROLE
* @param hook New hook address to set
*/
function setHookAddress(address hook) external;
/**
* @notice Updates the address of the Cash Module
* @dev Only callable by addresses with ADMIN_ROLE
* @param cashModule New cash module address to set
*/
function setCashModule(address cashModule) external;
/**
* @notice Checks if a module address is whitelisted
* @param module Address to check
* @return bool True if the module is whitelisted, false otherwise
*/
function isWhitelistedModule(address module) external view returns (bool);
/**
* @notice Checks if a module address is a whitelisted default module
* @param module Address to check
* @return bool True if the module is a whitelisted default module, false otherwise
*/
function isDefaultModule(address module) external view returns (bool);
/**
* @notice Retrieves all whitelisted module addresses
* @return address[] Array of whitelisted module addresses
*/
function getWhitelistedModules() external view returns (address[] memory);
/**
* @notice Returns the address of the Cash Module
* @return Address of the cash module
*/
function getCashModule() external view returns (address);
/**
* @notice Returns the address of the EtherFi Recovery signer
* @return Address of the EtherFi Recovery Signer
*/
function getEtherFiRecoverySigner() external view returns (address);
/**
* @notice Returns the address of the Third Party Recovery signer
* @return Address of the Third Party Recovery Signer
*/
function getThirdPartyRecoverySigner() external view returns (address);
/**
* @notice Returns the address of the Refund wallet
* @return Address of the Refund wallet
*/
function getRefundWallet() external view returns (address);
/**
* @notice Returns the Recovery delay period in seconds
* @return Recovery delay period in seconds
*/
function getRecoveryDelayPeriod() external view returns (uint256);
/**
* @notice Returns the address of the Cash Lens contract
* @return Address of the Cash Lens contract
*/
function getCashLens() external view returns (address);
/**
* @notice Returns the address of the Price provider contract
* @return Address of the Price provider contract
*/
function getPriceProvider() external view returns (address);
/**
* @notice Returns the current hook address
* @return address Current hook address
*/
function getHookAddress() external view returns (address);
function getEtherFiSafeFactory() external view returns (address);
/**
* @notice Function to check if an account is an EtherFiSafe
* @param account Address of the account to check
*/
function isEtherFiSafe(address account) external view returns (bool);
/**
* @notice Role identifier for administrative privileges
* @return bytes32 The keccak256 hash of "ADMIN_ROLE"
*/
function ADMIN_ROLE() external view returns (bytes32);
/**
* @notice Returns the address of the Role Registry contract
* @return roleRegistry Reference to the role registry contract
*/
function roleRegistry() external view returns (IRoleRegistry);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IPriceProvider {
error UnknownToken();
/**
* @notice Function to get the price of a token in USD
* @return Price with 6 decimals
*/
function price(address token) external view returns (uint256);
/**
* @notice Function to fetch the admin role
* @return PRICE_PROVIDER_ADMIN_ROLE
*/
function PRICE_PROVIDER_ADMIN_ROLE() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { TimeLib } from "./TimeLib.sol";
/**
* @title SpendingLimit
* @notice Data structure for managing daily and monthly spending limits with time-based renewals
* @dev Includes current limits, spent amounts, pending limit changes, and renewal timestamps
*/
struct SpendingLimit {
uint256 dailyLimit; // in USD with 6 decimals
uint256 monthlyLimit; // in USD with 6 decimals
uint256 spentToday; // in USD with 6 decimals
uint256 spentThisMonth; // in USD with 6 decimals
uint256 newDailyLimit; // in USD with 6 decimals
uint256 newMonthlyLimit; // in USD with 6 decimals
uint64 dailyRenewalTimestamp;
uint64 monthlyRenewalTimestamp;
uint64 dailyLimitChangeActivationTime;
uint64 monthlyLimitChangeActivationTime;
int256 timezoneOffset;
}
/**
* @title SpendingLimitLib
* @notice Library for managing spending limits with daily and monthly caps
* @dev Provides functionality for initializing, updating, and enforcing spending limits
* @author ether.fi
*/
library SpendingLimitLib {
using TimeLib for uint256;
using Math for uint256;
/**
* @notice Error thrown when a spend would exceed the daily limit
*/
error ExceededDailySpendingLimit();
/**
* @notice Error thrown when a spend would exceed the monthly limit
*/
error ExceededMonthlySpendingLimit();
/**
* @notice Error thrown when daily limit is set higher than monthly limit
*/
error DailyLimitCannotBeGreaterThanMonthlyLimit();
/**
* @notice Error thrown when timezone offset is invalid
*/
error InvalidTimezoneOffset();
/**
* @notice Initializes a new SpendingLimit with daily and monthly caps
* @dev Sets up initial renewal timestamps based on current time and timezone offset
* @param limit Storage reference to the SpendingLimit to initialize
* @param dailyLimit Maximum amount that can be spent in a day (USD with 6 decimals)
* @param monthlyLimit Maximum amount that can be spent in a month (USD with 6 decimals)
* @param timezoneOffset User's timezone offset in seconds
* @return The initialized SpendingLimit
* @custom:throws DailyLimitCannotBeGreaterThanMonthlyLimit if daily limit exceeds monthly limit
* @custom:throws InvalidTimezoneOffset if timezone offset is outside valid range
*/
function initialize(SpendingLimit storage limit, uint256 dailyLimit, uint256 monthlyLimit, int256 timezoneOffset) internal sanity(dailyLimit, monthlyLimit) returns (SpendingLimit memory) {
if (timezoneOffset > 24 * 60 * 60 || timezoneOffset < -24 * 60 * 60) revert InvalidTimezoneOffset();
limit.dailyLimit = dailyLimit;
limit.monthlyLimit = monthlyLimit;
limit.timezoneOffset = timezoneOffset;
limit.dailyRenewalTimestamp = block.timestamp.getStartOfNextDay(limit.timezoneOffset);
limit.monthlyRenewalTimestamp = block.timestamp.getStartOfNextMonth(limit.timezoneOffset);
return limit;
}
/**
* @notice Updates storage with the current limit state
* @dev Refreshes all fields of the limit struct with current values
* @param limit Storage reference to the SpendingLimit to update
*/
function currentLimit(SpendingLimit storage limit) internal {
SpendingLimit memory finalLimit = getCurrentLimit(limit);
limit.dailyLimit = finalLimit.dailyLimit;
limit.monthlyLimit = finalLimit.monthlyLimit;
limit.spentToday = finalLimit.spentToday;
limit.spentThisMonth = finalLimit.spentThisMonth;
limit.newDailyLimit = finalLimit.newDailyLimit;
limit.newMonthlyLimit = finalLimit.newMonthlyLimit;
limit.dailyRenewalTimestamp = finalLimit.dailyRenewalTimestamp;
limit.monthlyRenewalTimestamp = finalLimit.monthlyRenewalTimestamp;
limit.dailyLimitChangeActivationTime = finalLimit.dailyLimitChangeActivationTime;
limit.monthlyLimitChangeActivationTime = finalLimit.monthlyLimitChangeActivationTime;
}
/**
* @notice Records a spend against the daily and monthly limits
* @dev Updates current limits first, then applies the spend if within limits
* @param limit Storage reference to the SpendingLimit
* @param amount Amount to spend (USD with 6 decimals)
* @custom:throws ExceededDailySpendingLimit if spend would exceed daily limit
* @custom:throws ExceededMonthlySpendingLimit if spend would exceed monthly limit
*/
function spend(SpendingLimit storage limit, uint256 amount) internal {
currentLimit(limit);
if (limit.spentToday + amount > limit.dailyLimit) revert ExceededDailySpendingLimit();
if (limit.spentThisMonth + amount > limit.monthlyLimit) revert ExceededMonthlySpendingLimit();
limit.spentToday += amount;
limit.spentThisMonth += amount;
}
/**
* @notice Updates spending limits with optional delay for decreases
* @dev Immediate increases, delayed decreases with activation timestamp
* @param limit Storage reference to the SpendingLimit
* @param newDailyLimit New daily spending limit (USD with 6 decimals)
* @param newMonthlyLimit New monthly spending limit (USD with 6 decimals)
* @param delay Seconds to delay limit decreases (0 for immediate)
* @return Original limit before changes
* @return Updated limit after changes
* @custom:throws DailyLimitCannotBeGreaterThanMonthlyLimit if daily limit exceeds monthly limit
*/
function updateSpendingLimit(SpendingLimit storage limit, uint256 newDailyLimit, uint256 newMonthlyLimit, uint64 delay) internal sanity(newDailyLimit, newMonthlyLimit) returns (SpendingLimit memory, SpendingLimit memory) {
currentLimit(limit);
SpendingLimit memory oldLimit = limit;
if (newDailyLimit < limit.dailyLimit) {
limit.newDailyLimit = newDailyLimit;
limit.dailyLimitChangeActivationTime = uint64(block.timestamp) + delay;
} else {
limit.dailyLimit = newDailyLimit;
limit.newDailyLimit = 0;
limit.dailyLimitChangeActivationTime = 0;
}
if (newMonthlyLimit < limit.monthlyLimit) {
limit.newMonthlyLimit = newMonthlyLimit;
limit.monthlyLimitChangeActivationTime = uint64(block.timestamp) + delay;
} else {
limit.monthlyLimit = newMonthlyLimit;
limit.newMonthlyLimit = 0;
limit.monthlyLimitChangeActivationTime = 0;
}
return (oldLimit, limit);
}
/**
* @notice Calculates the maximum amount that can be spent right now
* @dev Considers both daily and monthly limits, returning the lower of the two remaining amounts
* @param limit Memory copy of the SpendingLimit
* @return Maximum spendable amount in USD with 6 decimals
*/
function maxCanSpend(SpendingLimit memory limit) internal view returns (uint256) {
limit = getCurrentLimit(limit);
bool usingIncomingDailyLimit = false;
bool usingIncomingMonthlyLimit = false;
uint256 applicableDailyLimit = limit.dailyLimit;
uint256 applicableMonthlyLimit = limit.monthlyLimit;
if (limit.dailyLimitChangeActivationTime != 0) {
applicableDailyLimit = limit.newDailyLimit;
usingIncomingDailyLimit = true;
}
if (limit.monthlyLimitChangeActivationTime != 0) {
applicableMonthlyLimit = limit.newMonthlyLimit;
usingIncomingMonthlyLimit = true;
}
if (limit.spentToday > applicableDailyLimit) return 0;
if (limit.spentThisMonth > applicableMonthlyLimit) return 0;
return Math.min(applicableDailyLimit - limit.spentToday, applicableMonthlyLimit - limit.spentThisMonth);
}
/**
* @notice Checks if a specific amount can be spent
* @dev Considers both daily and monthly limits, including pending limit changes
* @param limit Memory copy of the SpendingLimit
* @param amount Amount to check if spendable (USD with 6 decimals)
* @return canSpend Boolean indicating if the amount can be spent
* @return message Error message if amount cannot be spent
*/
function canSpend(SpendingLimit memory limit, uint256 amount) internal view returns (bool, string memory) {
limit = getCurrentLimit(limit);
bool usingIncomingDailyLimit = false;
bool usingIncomingMonthlyLimit = false;
uint256 applicableDailyLimit = limit.dailyLimit;
uint256 applicableMonthlyLimit = limit.monthlyLimit;
if (limit.dailyLimitChangeActivationTime != 0) {
applicableDailyLimit = limit.newDailyLimit;
usingIncomingDailyLimit = true;
}
if (limit.monthlyLimitChangeActivationTime != 0) {
applicableMonthlyLimit = limit.newMonthlyLimit;
usingIncomingMonthlyLimit = true;
}
if (limit.spentToday > applicableDailyLimit) {
if (usingIncomingDailyLimit) return (false, "Incoming daily spending limit already exhausted");
else return (false, "Daily spending limit already exhausted");
}
if (limit.spentThisMonth > applicableMonthlyLimit) {
if (usingIncomingMonthlyLimit) return (false, "Incoming monthly spending limit already exhausted");
else return (false, "Monthly spending limit already exhausted");
}
uint256 availableDaily = applicableDailyLimit - limit.spentToday;
uint256 availableMonthly = applicableMonthlyLimit - limit.spentThisMonth;
if (amount > availableDaily) {
if (usingIncomingDailyLimit) return (false, "Incoming daily available spending limit less than amount requested");
return (false, "Daily available spending limit less than amount requested");
}
if (amount > availableMonthly) {
if (usingIncomingMonthlyLimit) return (false, "Incoming monthly available spending limit less than amount requested");
return (false, "Monthly available spending limit less than amount requested");
}
return (true, "");
}
/**
* @notice Gets the current limit state with all time-based updates applied
* @dev Applies pending limit changes and resets counters on renewal timestamps
* @param limit Memory copy of the SpendingLimit
* @return Updated SpendingLimit reflecting current state
*/
function getCurrentLimit(SpendingLimit memory limit) internal view returns (SpendingLimit memory) {
if (limit.dailyLimitChangeActivationTime != 0 && block.timestamp > limit.dailyLimitChangeActivationTime) {
limit.dailyLimit = limit.newDailyLimit;
limit.newDailyLimit = 0;
limit.dailyLimitChangeActivationTime = 0;
}
if (limit.monthlyLimitChangeActivationTime != 0 && block.timestamp > limit.monthlyLimitChangeActivationTime) {
limit.monthlyLimit = limit.newMonthlyLimit;
limit.newMonthlyLimit = 0;
limit.monthlyLimitChangeActivationTime = 0;
}
if (block.timestamp > limit.dailyRenewalTimestamp) {
limit.spentToday = 0;
limit.dailyRenewalTimestamp = getFinalDailyRenewalTimestamp(limit.dailyRenewalTimestamp, limit.timezoneOffset);
}
if (block.timestamp > limit.monthlyRenewalTimestamp) {
limit.spentThisMonth = 0;
limit.monthlyRenewalTimestamp = getFinalMonthlyRenewalTimestamp(limit.monthlyRenewalTimestamp, limit.timezoneOffset);
}
return limit;
}
/**
* @notice Calculates the next valid daily renewal timestamp
* @dev Handles cases where multiple renewal periods have elapsed
* @param renewalTimestamp Current renewal timestamp
* @param timezoneOffset User's timezone offset in seconds
* @return Next valid daily renewal timestamp
*/
function getFinalDailyRenewalTimestamp(uint64 renewalTimestamp, int256 timezoneOffset) internal view returns (uint64) {
do {
renewalTimestamp = uint256(renewalTimestamp).getStartOfNextDay(timezoneOffset);
} while (block.timestamp > renewalTimestamp);
return renewalTimestamp;
}
/**
* @notice Calculates the next valid monthly renewal timestamp
* @dev Handles cases where multiple renewal periods have elapsed
* @param renewalTimestamp Current renewal timestamp
* @param timezoneOffset User's timezone offset in seconds
* @return Next valid monthly renewal timestamp
*/
function getFinalMonthlyRenewalTimestamp(uint64 renewalTimestamp, int256 timezoneOffset) internal view returns (uint64) {
do {
renewalTimestamp = uint256(renewalTimestamp).getStartOfNextMonth(timezoneOffset);
} while (block.timestamp > renewalTimestamp);
return renewalTimestamp;
}
/**
* @dev Modifier to ensure daily limit is not greater than monthly limit
* @param dailyLimit Daily spending limit to validate
* @param monthlyLimit Monthly spending limit to validate
* @custom:throws DailyLimitCannotBeGreaterThanMonthlyLimit if daily limit exceeds monthly limit
*/
modifier sanity(uint256 dailyLimit, uint256 monthlyLimit) {
if (dailyLimit > monthlyLimit) revert DailyLimitCannotBeGreaterThanMonthlyLimit();
_;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { IERC1271 } from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @title Library of utilities for making EIP1271-compliant signature checks
* @author ether.fi
* @notice Provides functions to verify signatures from both EOAs and smart contracts implementing EIP-1271
* @dev Implements signature verification following EIP-1271 standard for smart contracts
* and standard ECDSA verification for EOAs
*/
library SignatureUtils {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 internal constant EIP1271_MAGICVALUE = 0x1626ba7e;
/// @notice Thrown when an EOA signature is invalid
error InvalidSigner();
/// @notice Thrown when an ERC1271 contract signature verification fails
error InvalidERC1271Signer();
/**
* @notice Verifies if a signature is valid according to EIP-1271 standards
* @dev For EOAs, uses ECDSA recovery. For contracts, calls EIP-1271 isValidSignature
* @param digestHash The hash of the data that was signed
* @param signer The address that should have signed the data
* @param signature The signature bytes
* @custom:security Consider that contract signatures might have different gas costs
* @custom:warning The isContract check may return false positives during contract construction
* @custom:throws InvalidSigner If the EOA signature is invalid
* @custom:throws InvalidERC1271Signer If the contract signature verification fails
*/
function checkSignature(bytes32 digestHash, address signer, bytes memory signature) internal view {
if (isContract(signer)) {
if (IERC1271(signer).isValidSignature(digestHash, signature) != EIP1271_MAGICVALUE) revert InvalidERC1271Signer();
} else {
if (ECDSA.recover(digestHash, signature) != signer) revert InvalidSigner();
}
}
/**
* @notice Returns whether a signature is valid according to EIP-1271 standards
* @dev Similar to checkSignature_EIP1271 but returns boolean instead of reverting
* @param digestHash The hash of the data that was signed
* @param signer The address that should have signed the data
* @param signature The signature bytes
* @return bool True if the signature is valid, false otherwise
* @custom:warning The isContract check may return false positives during contract construction
*/
function isValidSignature(bytes32 digestHash, address signer, bytes memory signature) internal view returns (bool) {
if (isContract(signer)) {
return IERC1271(signer).isValidSignature(digestHash, signature) == EIP1271_MAGICVALUE;
} else {
return ECDSA.recover(digestHash, signature) == signer;
}
}
/**
* @notice Determines if an address is a contract
* @dev Uses assembly to check if the address has code
* @param account The address to check
* @return bool True if the address has code (is a contract), false otherwise
* @custom:warning This function returns false for contracts during their construction
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly ("memory-safe") {
size := extcodesize(account)
}
return size > 0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/**
* @title Constants
* @author ether.fi
* @notice Contract that defines commonly used constants across the ether.fi protocol
* @dev This contract is not meant to be deployed but to be inherited by other contracts
*/
contract Constants {
/**
* @notice Special address used to represent native ETH in the protocol
* @dev This address is used as a marker since ETH is not an ERC20 token
*/
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
library TimeLib {
// Function to find the timestamp for the start of the next day (00:00 in the user's time zone)
function getStartOfNextDay(uint256 timestamp, int256 timezoneOffset) internal pure returns (uint64) {
// Adjust the timestamp for the time zone offset
int256 adjustedTimestamp = int256(timestamp) + timezoneOffset;
// Calculate the current day in the adjusted time zone
uint256 currentDay = uint256(adjustedTimestamp / 1 days);
// Calculate the start of the next day in the adjusted time zone
uint256 startOfNextDay = (currentDay + 1) * 1 days;
// Adjust the result back to the user's local time zone
return uint64(uint256(int256(startOfNextDay) - timezoneOffset));
}
// Function to find the start of the next week (Monday 00:00 in the user's time zone)
function getStartOfNextWeek(uint256 timestamp, int256 timezoneOffset) internal pure returns (uint64) {
// Adjust the timestamp for the time zone offset
int256 adjustedTimestamp = int256(timestamp) + timezoneOffset;
// Calculate the current day of the week (0 = Monday, 6 = Sunday)
uint256 dayOfWeek = (uint256(adjustedTimestamp) / 1 days + 3) % 7;
// Calculate the number of days until the next Monday
uint256 daysUntilNextMonday = (dayOfWeek == 0) ? 7 : (7 - dayOfWeek);
// Calculate the start of the next week in the adjusted time zone
uint256 startOfNextWeek = ((uint256(adjustedTimestamp) / 1 days) + daysUntilNextMonday) * 1 days;
// Adjust the result back to the user's local time zone
return uint64(uint256(int256(startOfNextWeek) - timezoneOffset));
}
// Function to find the start of the next month (in the user's time zone)
function getStartOfNextMonth(uint256 timestamp, int256 timezoneOffset) internal pure returns (uint64) {
// Adjust the timestamp for the time zone offset
int256 adjustedTimestamp = int256(timestamp) + timezoneOffset;
// Get the current date in the adjusted time zone
(uint16 year, uint8 month,) = _daysToDate(uint256(adjustedTimestamp) / 1 days);
// Increment the month and adjust the year if necessary
month += 1;
if (month > 12) {
month = 1;
year += 1;
}
// Calculate the start of the next month in the adjusted time zone
uint256 startOfNextMonth = _daysFromDate(year, month, 1) * 1 days;
// Adjust the result back to the user's local time zone
return uint64(uint256(int256(startOfNextMonth) - timezoneOffset));
}
// Internal function to calculate days from date
function _daysFromDate(uint16 year, uint8 month, uint8 day) internal pure returns (uint256) {
int256 _year = int256(uint256(year));
int256 _month = int256(uint256(month));
int256 _day = int256(uint256(day));
int256 __days = _day - 32_075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - 2_440_588;
return uint256(__days);
}
// Internal function to convert days to date
function _daysToDate(uint256 _days) internal pure returns (uint16 year, uint8 month, uint8 day) {
int256 __days = int256(_days);
int256 L = __days + 68_569 + 2_440_588;
int256 N = 4 * L / 146_097;
L = L - (146_097 * N + 3) / 4;
int256 _year = 4000 * (L + 1) / 1_461_001;
L = L - 1461 * _year / 4 + 31;
int256 _month = 80 * L / 2447;
int256 _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint16(uint256(_year));
month = uint8(uint256(_month));
day = uint8(uint256(_day));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1271.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}{
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solady/=lib/solady/src/"
],
"optimizer": {
"enabled": true,
"runs": 50
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "none",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false,
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address[]","name":"_assets","type":"address[]"},{"internalType":"address[]","name":"_tellers","type":"address[]"},{"internalType":"address","name":"_etherFiDataProvider","type":"address"},{"internalType":"address","name":"_weth","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AmountNotAvailable","type":"error"},{"inputs":[],"name":"ArrayLengthMismatch","type":"error"},{"inputs":[],"name":"AssetNotSupportedForDeposit","type":"error"},{"inputs":[],"name":"CannotFindMatchingWithdrawalForSafe","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[],"name":"InsufficientAvailableBalanceOnSafe","type":"error"},{"inputs":[],"name":"InsufficientNativeFee","type":"error"},{"inputs":[],"name":"InsufficientReturnAmount","type":"error"},{"inputs":[],"name":"InvalidBoringQueue","type":"error"},{"inputs":[],"name":"InvalidConfiguration","type":"error"},{"inputs":[],"name":"InvalidInput","type":"error"},{"inputs":[],"name":"InvalidSignature","type":"error"},{"inputs":[],"name":"InvalidSignatures","type":"error"},{"inputs":[],"name":"InvalidValue","type":"error"},{"inputs":[],"name":"LiquidWithdrawConfigNotSet","type":"error"},{"inputs":[],"name":"NativeTransferFailed","type":"error"},{"inputs":[],"name":"NoWithdrawalQueuedForLiquid","type":"error"},{"inputs":[],"name":"OnlyEtherFiSafe","type":"error"},{"inputs":[],"name":"OnlySafeAdmin","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"UnsupportedLiquidAsset","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address[]","name":"liquidAssets","type":"address[]"},{"indexed":false,"internalType":"address[]","name":"tellers","type":"address[]"}],"name":"LiquidAssetsAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address[]","name":"liquidAssets","type":"address[]"}],"name":"LiquidAssetsRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"safe","type":"address"},{"indexed":true,"internalType":"address","name":"liquidAsset","type":"address"},{"indexed":false,"internalType":"uint32","name":"destEid","type":"uint32"},{"indexed":true,"internalType":"address","name":"destRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"LiquidBridgeCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"safe","type":"address"},{"indexed":true,"internalType":"address","name":"liquidAsset","type":"address"},{"indexed":true,"internalType":"address","name":"destRecipient","type":"address"},{"indexed":false,"internalType":"uint32","name":"destEid","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bridgeFee","type":"uint256"}],"name":"LiquidBridgeExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"safe","type":"address"},{"indexed":true,"internalType":"address","name":"liquidAsset","type":"address"},{"indexed":false,"internalType":"uint32","name":"destEid","type":"uint32"},{"indexed":true,"internalType":"address","name":"destRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"LiquidBridgeRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"safe","type":"address"},{"indexed":true,"internalType":"address","name":"inputToken","type":"address"},{"indexed":true,"internalType":"address","name":"outputToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"inputAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"outputAmount","type":"uint256"}],"name":"LiquidDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"boringQueue","type":"address"}],"name":"LiquidWithdrawQueueSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"safe","type":"address"},{"indexed":true,"internalType":"address","name":"liquidAsset","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountToWithdraw","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"LiquidWithdrawal","type":"event"},{"inputs":[],"name":"CANCEL_BRIDGE_SIG","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEPOSIT_SIG","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ETHERFI_LIQUID_MODULE_ADMIN","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REQUEST_BRIDGE_SIG","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WITHDRAW_SIG","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"liquidAssets","type":"address[]"},{"internalType":"address[]","name":"tellers","type":"address[]"}],"name":"addLiquidAssets","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"},{"internalType":"address[]","name":"signers","type":"address[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"cancelBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"}],"name":"cancelBridgeByCashModule","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"cashModule","outputs":[{"internalType":"contract ICashModule","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"},{"internalType":"address","name":"assetToDeposit","type":"address"},{"internalType":"address","name":"liquidAsset","type":"address"},{"internalType":"uint256","name":"amountToDeposit","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"address","name":"signer","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"etherFiDataProvider","outputs":[{"internalType":"contract IEtherFiDataProvider","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"}],"name":"executeBridge","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"liquidAsset","type":"address"},{"internalType":"uint32","name":"destEid","type":"uint32"},{"internalType":"address","name":"destRecipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"getBridgeFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"}],"name":"getBridgeFeeForSafe","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"getLiquidAssetWithdrawQueue","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"}],"name":"getNonce","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"}],"name":"getPendingBridge","outputs":[{"components":[{"internalType":"uint32","name":"destEid","type":"uint32"},{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"destRecipient","type":"address"}],"internalType":"struct EtherFiLiquidModule.LiquidCrossChainWithdrawal","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"liquidAssetToTeller","outputs":[{"internalType":"contract ILayerZeroTeller","name":"teller","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"liquidToken","type":"address"}],"name":"liquidWithdrawQueue","outputs":[{"internalType":"address","name":"boringQueue","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"liquidAssets","type":"address[]"}],"name":"removeLiquidAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"},{"internalType":"uint32","name":"destEid","type":"uint32"},{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"destRecipient","type":"address"},{"internalType":"address[]","name":"signers","type":"address[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"requestBridge","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"address","name":"boringQueue","type":"address"}],"name":"setLiquidAssetWithdrawQueue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"setupModule","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"weth","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"safe","type":"address"},{"internalType":"address","name":"liquidAsset","type":"address"},{"internalType":"address","name":"assetOut","type":"address"},{"internalType":"uint128","name":"amountToWithdraw","type":"uint128"},{"internalType":"uint128","name":"minReturn","type":"uint128"},{"internalType":"uint16","name":"discount","type":"uint16"},{"internalType":"uint24","name":"secondsToDeadline","type":"uint24"},{"internalType":"address","name":"signer","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
0x60e060405234801561000f575f5ffd5b5060405161496f38038061496f83398101604081905261002e91610404565b81806001600160a01b0381166100575760405163b4fa3fb360e01b815260040160405180910390fd5b806001600160a01b03166080816001600160a01b03168152505050806001600160a01b031663882d16986040518163ffffffff1660e01b8152600401602060405180830381865afa1580156100ae573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906100d2919061048e565b6001600160a01b031660a052508351835181146101025760405163512509d360e11b815260040160405180910390fd5b6001600160a01b038316158061011f57506001600160a01b038216155b1561013d5760405163b4fa3fb360e01b815260040160405180910390fd5b6001600160a01b03821660c0525f5b8181101561031b575f6001600160a01b0316868281518110610170576101706104b0565b60200260200101516001600160a01b031614806101b757505f6001600160a01b03168582815181106101a4576101a46104b0565b60200260200101516001600160a01b0316145b156101d55760405163b4fa3fb360e01b815260040160405180910390fd5b8581815181106101e7576101e76104b0565b60200260200101516001600160a01b031685828151811061020a5761020a6104b0565b60200260200101516001600160a01b031663fbfa77cf6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561024d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610271919061048e565b6001600160a01b0316146102985760405163c52a9bd360e01b815260040160405180910390fd5b8481815181106102aa576102aa6104b0565b60200260200101515f5f8884815181106102c6576102c66104b0565b60200260200101516001600160a01b03166001600160a01b031681526020019081526020015f205f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555080600101905061014c565b5050505050506104c4565b634e487b7160e01b5f52604160045260245ffd5b6001600160a01b038116811461034e575f5ffd5b50565b805161035c8161033a565b919050565b5f82601f830112610370575f5ffd5b81516001600160401b0381111561038957610389610326565b604051600582901b90603f8201601f191681016001600160401b03811182821017156103b7576103b7610326565b6040529182526020818501810192908101868411156103d4575f5ffd5b6020860192505b838310156103fa576103ec83610351565b8152602092830192016103db565b5095945050505050565b5f5f5f5f60808587031215610417575f5ffd5b84516001600160401b0381111561042c575f5ffd5b61043887828801610361565b602087015190955090506001600160401b03811115610455575f5ffd5b61046187828801610361565b93505060408501516104728161033a565b60608601519092506104838161033a565b939692955090935050565b5f6020828403121561049e575f5ffd5b81516104a98161033a565b9392505050565b634e487b7160e01b5f52603260045260245ffd5b60805160a05160c0516143f561057a5f395f81816102950152818161214401528181612239015281816122e701526123dc01525f818161024201528181610b7201528181610cac01528181610ec301528181610f7301528181612efb01528181612fa7015261324e01525f81816105eb0152818161060f0152818161086d01528181610a5301528181610d97015281816110dd01528181611248015281816113a2015281816117350152611a2101526143f55ff3fe60806040526004361061013f575f3560e01c806371e5dc81116100af57806371e5dc811461035b5780637c0691b31461037a5780638322fff2146103995780638a2e5c3d146103c0578063909030d5146103f35780639e673bc314610411578063a66e9d0a14610444578063b176806514610463578063c760e2ff14610496578063ceb5724714610575578063d17a613114610588578063d41f1771146105a7578063f9fba81b146105da575f5ffd5b80630a44077a146101435780631eb2b17e1461018d5780632b03a50c146101c45780632d0335ab146101e55780632db274c8146102125780633575f0de1461023157806339f1bc2c146102645780633fc8cef31461028457806343832054146102b75780635988e7a1146102eb57806360b72616146102fe57806363baa2601461031d578063709b0f511461033c575b5f5ffd5b34801561014e575f5ffd5b5061017761015d366004613566565b5f602081905290815260409020546001600160a01b031681565b6040516101849190613581565b60405180910390f35b348015610198575f5ffd5b506101776101a7366004613566565b6001600160a01b039081165f908152600160205260409020541690565b3480156101cf575f5ffd5b506101e36101de366004613595565b61060d565b005b3480156101f0575f5ffd5b506102046101ff366004613566565b610844565b604051908152602001610184565b34801561021d575f5ffd5b506101e361022c366004613566565b61086b565b34801561023c575f5ffd5b506101777f000000000000000000000000000000000000000000000000000000000000000081565b34801561026f575f5ffd5b506102045f5160206143a95f395f51905f5281565b34801561028f575f5ffd5b506101777f000000000000000000000000000000000000000000000000000000000000000081565b3480156102c2575f5ffd5b506101776102d1366004613566565b60016020525f90815260409020546001600160a01b031681565b6101e36102f9366004613566565b610a32565b348015610309575f5ffd5b506101e3610318366004613613565b610d76565b348015610328575f5ffd5b506101e36103373660046136d0565b6110c4565b348015610347575f5ffd5b506101e361035636600461379f565b61122f565b348015610366575f5ffd5b506101e3610375366004613870565b6113a0565b348015610385575f5ffd5b506101e36103943660046138da565b611733565b3480156103a4575f5ffd5b5061017773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b3480156103cb575f5ffd5b506102047f6aa129b587db2f56b32662e4af4556cdc69b6228434cb2791c6377894b40bf2c81565b3480156103fe575f5ffd5b506101e361040d366004613918565b5050565b34801561041c575f5ffd5b506102047f7360ecb005ef445b1cb2b3a294f2c499b088f258b4531fffbc4c244d8cf7732381565b34801561044f575f5ffd5b5061020461045e36600461395d565b61190a565b34801561046e575f5ffd5b506102047f855511cc3694f64379908437d6d64458dc76d02482052bfb8a5b33a72c054c7781565b3480156104a1575f5ffd5b5061052d6104b0366004613566565b604080516080810182525f808252602082018190529181018290526060810191909152506001600160a01b039081165f908152600260208181526040928390208351608081018552815463ffffffff81168252600160201b9004861692810192909252600181015493820193909352910154909116606082015290565b6040516101849190815163ffffffff1681526020808301516001600160a01b039081169183019190915260408084015190830152606092830151169181019190915260800190565b6101e36105833660046139a9565b611a00565b348015610593575f5ffd5b506102046105a2366004613566565b611ae4565b3480156105b2575f5ffd5b506102047f48c73f681176fc7b3f9693986fd7b14581e8d540519e27400e88b8713932be0181565b3480156105e5575f5ffd5b506101777f000000000000000000000000000000000000000000000000000000000000000081565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166308c732596040518163ffffffff1660e01b8152600401602060405180830381865afa158015610669573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061068d9190613a68565b6001600160a01b03166391d148545f5160206143a95f395f51905f52336040518363ffffffff1660e01b81526004016106c7929190613a83565b602060405180830381865afa1580156106e2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107069190613aa9565b610722576040516282b42960e81b815260040160405180910390fd5b6001600160a01b038216158061073f57506001600160a01b038116155b1561075d57604051632a9ffab760e21b815260040160405180910390fd5b806001600160a01b031663f3b977846040518163ffffffff1660e01b8152600401602060405180830381865afa158015610799573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107bd9190613a68565b6001600160a01b0316826001600160a01b0316146107ee576040516335c66c9960e01b815260040160405180910390fd5b6001600160a01b038281165f8181526001602052604080822080546001600160a01b0319169486169485179055517fdd001770b3f22fb8a32aee0705976d01646098f9c1254e8064d2ee09184490189190a35050565b5f61084d611b7e565b6001600160a01b039092165f90815260209290925250604090205490565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663882d16986040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108c7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108eb9190613a68565b6001600160a01b0316336001600160a01b03161461091b576040516282b42960e81b815260040160405180910390fd5b6001600160a01b038082165f908152600260208181526040928390208351608081018552815463ffffffff81168252600160201b90048616928101929092526001810154938201939093529101549091166060820181905261097b575050565b80606001516001600160a01b031681602001516001600160a01b0316836001600160a01b03167f2e3c65d07c4fc7496e4f35bdc83c653debda281afe443cf6f2d2b0e4d02d6783845f015185604001516040516109ea92919063ffffffff929092168252602082015260400190565b60405180910390a4506001600160a01b03165f908152600260208190526040822080546001600160c01b031916815560018101929092550180546001600160a01b0319169055565b610a3a611ba2565b60405163b7ca418b60e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063b7ca418b90610a88908490600401613581565b602060405180830381865afa158015610aa3573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ac79190613aa9565b610ae4576040516334d0b49960e01b815260040160405180910390fd5b6001600160a01b038083165f908152600260208181526040928390208351608081018552815463ffffffff81168252600160201b900486169281019290925260018101549382019390935291015490911660608201819052610b5957604051638a88784960e01b815260040160405180910390fd5b604051631c13359160e11b81525f906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906338266b2290610ba7908790600401613581565b5f60405180830381865afa158015610bc1573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610be89190810190613de0565b6020015160408101519091506001600160a01b031630141580610c0e5750805151600114155b80610c4b575081602001516001600160a01b0316815f01515f81518110610c3757610c37613e98565b60200260200101516001600160a01b031614155b80610c775750816040015181602001515f81518110610c6c57610c6c613e98565b602002602001015114155b15610c955760405163a78fbb5f60e01b815260040160405180910390fd5b604051631e0d280960e11b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690633c1a501290610ce1908790600401613581565b5f604051808303815f87803b158015610cf8575f5ffd5b505af1158015610d0a573d5f5f3e3d5ffd5b50505050610d2a848360200151845f015185606001518660400151611beb565b5050506001600160a01b0381165f908152600260208190526040822080546001600160c01b031916815560018101929092550180546001600160a01b0319169055610d73611ddb565b50565b610d7e611ba2565b60405163b7ca418b60e01b815285906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063b7ca418b90610dcc908490600401613581565b602060405180830381865afa158015610de7573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0b9190613aa9565b610e28576040516334d0b49960e01b815260040160405180910390fd5b610e358686868686611df2565b6001600160a01b038087165f908152600260208181526040928390208351608081018552815463ffffffff81168252600160201b900486169281019290925260018101549382019390935291015490911660608201819052610eaa57604051638a88784960e01b815260040160405180910390fd5b604051631c13359160e11b81525f906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906338266b2290610ef8908b90600401613581565b5f60405180830381865afa158015610f12573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610f399190810190613de0565b9050306001600160a01b03168160200151604001516001600160a01b031603610fd65760405163526cd20560e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a4d9a40a90610fa8908b90600401613581565b5f604051808303815f87803b158015610fbf575f5ffd5b505af1158015610fd1573d5f5f3e3d5ffd5b505050505b6001600160a01b038881165f90815260026020526040902054600160201b900416156110b25781606001516001600160a01b031682602001516001600160a01b0316896001600160a01b03167f2e3c65d07c4fc7496e4f35bdc83c653debda281afe443cf6f2d2b0e4d02d6783855f0151866040015160405161106b92919063ffffffff929092168252602082015260400190565b60405180910390a46001600160a01b0388165f908152600260208190526040822080546001600160c01b031916815560018101929092550180546001600160a01b03191690555b5050506110bd611ddb565b5050505050565b60405163b7ca418b60e01b815288906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063b7ca418b90611112908490600401613581565b602060405180830381865afa15801561112d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111519190613aa9565b61116e576040516334d0b49960e01b815260040160405180910390fd5b8884816001600160a01b03166324d7806c826040518263ffffffff1660e01b815260040161119c9190613581565b602060405180830381865afa1580156111b7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111db9190613aa9565b6111f857604051632afafb8760e21b815260040160405180910390fd5b5f6112068c8c8c8c8c611f98565b905061121481888888612025565b6112218c8c8c8c8c61208b565b505050505050505050505050565b60405163b7ca418b60e01b81528a906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063b7ca418b9061127d908490600401613581565b602060405180830381865afa158015611298573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112bc9190613aa9565b6112d9576040516334d0b49960e01b815260040160405180910390fd5b8a84816001600160a01b03166324d7806c826040518263ffffffff1660e01b81526004016113079190613581565b602060405180830381865afa158015611322573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113469190613aa9565b61136357604051632afafb8760e21b815260040160405180910390fd5b5f6113738e8e8e8e8e8e8e61285b565b905061138181888888612025565b6113908e8e8e8e8e8e8e6128ea565b5050505050505050505050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166308c732596040518163ffffffff1660e01b8152600401602060405180830381865afa1580156113fc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114209190613a68565b6001600160a01b03166391d148545f5160206143a95f395f51905f52336040518363ffffffff1660e01b815260040161145a929190613a83565b602060405180830381865afa158015611475573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114999190613aa9565b6114b5576040516282b42960e81b815260040160405180910390fd5b828181146114d65760405163512509d360e11b815260040160405180910390fd5b805f036114f65760405163b4fa3fb360e01b815260040160405180910390fd5b5f5b818110156116ee575f86868381811061151357611513613e98565b90506020020160208101906115289190613566565b6001600160a01b0316148061156b57505f84848381811061154b5761154b613e98565b90506020020160208101906115609190613566565b6001600160a01b0316145b156115895760405163b4fa3fb360e01b815260040160405180910390fd5b85858281811061159b5761159b613e98565b90506020020160208101906115b09190613566565b6001600160a01b03168484838181106115cb576115cb613e98565b90506020020160208101906115e09190613566565b6001600160a01b031663fbfa77cf6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561161b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061163f9190613a68565b6001600160a01b0316146116665760405163c52a9bd360e01b815260040160405180910390fd5b83838281811061167857611678613e98565b905060200201602081019061168d9190613566565b5f5f8888858181106116a1576116a1613e98565b90506020020160208101906116b69190613566565b6001600160a01b03908116825260208201929092526040015f2080546001600160a01b031916929091169190911790556001016114f8565b507feb3d2ee89a264650a8a29fb1c1be99f36ba69e616861cd44feb7cc77dca9fd53858585856040516117249493929190613ef4565b60405180910390a15050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166308c732596040518163ffffffff1660e01b8152600401602060405180830381865afa15801561178f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117b39190613a68565b6001600160a01b03166391d148545f5160206143a95f395f51905f52336040518363ffffffff1660e01b81526004016117ed929190613a83565b602060405180830381865afa158015611808573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061182c9190613aa9565b611848576040516282b42960e81b815260040160405180910390fd5b805f81900361186a5760405163b4fa3fb360e01b815260040160405180910390fd5b5f5b818110156118cb575f5f85858481811061188857611888613e98565b905060200201602081019061189d9190613566565b6001600160a01b0316815260208101919091526040015f2080546001600160a01b031916905560010161186c565b507f367cb6a9904bc3ce17bcf0727db772a2c5533312a93548f9714612928a9feeb483836040516118fd929190613f1a565b60405180910390a1505050565b6001600160a01b038085165f90815260208190526040812054909116806119445760405163f66d0cc960e01b815260040160405180910390fd5b6040805163ffffffff871660208201525f91016040516020818303038152906040529050816001600160a01b031663d7424e3361198086612cab565b878473eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6040518563ffffffff1660e01b81526004016119b69493929190613f63565b602060405180830381865afa1580156119d1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119f59190613fae565b979650505050505050565b611a08611ba2565b60405163b7ca418b60e01b815289906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063b7ca418b90611a56908490600401613581565b602060405180830381865afa158015611a71573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a959190613aa9565b611ab2576040516334d0b49960e01b815260040160405180910390fd5b611ac38a898b898b8a8a8a8a612ce7565b611ad08a898b898b612e51565b50611ad9611ddb565b505050505050505050565b6001600160a01b038082165f9081526002602081815260408084208151608081018352815463ffffffff81168252600160201b90048716938101939093526001810154918301919091529091015490921660608301819052909190611b5c57604051638a88784960e01b815260040160405180910390fd5b611b778160200151825f01518360600151846040015161190a565b9392505050565b7f9425b2e03e09da4c20ff7a465da264f7a02bf7079e1dbb47fce0436e1d206d0090565b5f5160206143c95f395f51905f525c15611bcf57604051633ee5aeb560e01b815260040160405180910390fd5b611be960015f5160206143c95f395f51905f525b906130e3565b565b6001600160a01b038085165f908152602081905260409020541680611c235760405163f66d0cc960e01b815260040160405180910390fd5b6040805163ffffffff861660208201525f910160405160208183030381529060405290505f826001600160a01b031663d7424e33611c6086612cab565b878573eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6040518563ffffffff1660e01b8152600401611c969493929190613f63565b602060405180830381865afa158015611cb1573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611cd59190613fae565b905080471015611cf857604051639c92bdfb60e01b815260040160405180910390fd5b826001600160a01b0316630592174082611d1187612cab565b888673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee876040518763ffffffff1660e01b8152600401611d49959493929190613fc5565b5f604051808303818588803b158015611d60575f5ffd5b505af1158015611d72573d5f5f3e3d5ffd5b50506040805163ffffffff8b168152602081018990529081018590526001600160a01b03808a1694508b811693508c1691507f089e0f7208f8fc06b9f41edffa576cac33d3135cb9f438dbb23abeebc96ea1949060600160405180910390a45050505050505050565b611be95f5f5160206143c95f395f51905f52611be3565b5f611efd7f6aa129b587db2f56b32662e4af4556cdc69b6228434cb2791c6377894b40bf2c4630896001600160a01b03166369615a4c6040518163ffffffff1660e01b81526004016020604051808303815f875af1158015611e56573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e7a9190613fae565b6040805160208101959095528401929092526001600160601b0319606091821b811682850152607484019290925289901b16609482015260a8015b604051602081830303815290604052805190602001207f19457468657265756d205369676e6564204d6573736167653a0a3332000000005f908152601c91909152603c902090565b60405163a732422d60e01b81529091506001600160a01b0387169063a732422d90611f34908490899089908990899060040161403c565b602060405180830381865afa158015611f4f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f739190613aa9565b611f905760405163274cf40160e01b815260040160405180910390fd5b505050505050565b5f61201b7f48c73f681176fc7b3f9693986fd7b14581e8d540519e27400e88b8713932be014630611fc88a6130ea565b604080516001600160a01b03808d1660208301528b169181019190915260608101899052608081018890528b9060a0015b60408051601f1981840301815290829052611eb59695949392916020016140f7565b9695505050505050565b6120688383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525089949392505061311b9050565b61208557604051638baa579f60e01b815260040160405180910390fd5b50505050565b6001600160a01b038084165f9081526020819052604090205416806120c35760405163f66d0cc960e01b815260040160405180910390fd5b8215806120ce575081155b156120ec5760405163b4fa3fb360e01b815260040160405180910390fd5b6120f78686856131ca565b6060808073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeed196001600160a01b0389160161245e576040516320ff722560e11b81526001600160a01b038516906341fee44a9061216c907f000000000000000000000000000000000000000000000000000000000000000090600401613581565b606060405180830381865afa158015612187573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121ab9190614148565b516121c9576040516308148def60e11b815260040160405180910390fd5b6040805160038082526080820190925290602082016060803683370190505060408051600380825260808201909252919450816020015b606081526020019060019003908161220057505060408051600380825260808201909252919350602082016060803683370190505090507f0000000000000000000000000000000000000000000000000000000000000000835f8151811061226a5761226a613e98565b6001600160a01b0390921660209283029190910182015260408051600481526024810190915290810180516001600160e01b0316630d0e30db60e41b179052825183905f906122bb576122bb613e98565b602002602001018190525085815f815181106122d9576122d9613e98565b6020026020010181815250507f00000000000000000000000000000000000000000000000000000000000000008360018151811061231957612319613e98565b6001600160a01b039092166020928302919091019091015260405163095ea7b360e01b9061234d90899089906024016141b5565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b0383818316178352505050508260018151811061239357612393613e98565b602002602001018190525083836002815181106123b2576123b2613e98565b6001600160a01b0390921660209283029190910190910152604051630efe6a8b60e01b90612408907f000000000000000000000000000000000000000000000000000000000000000090899089906024016141ce565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b0383818316178352505050508260028151811061244e5761244e613e98565b6020026020010181905250612687565b6040516320ff722560e11b81526001600160a01b038516906341fee44a9061248a908b90600401613581565b606060405180830381865afa1580156124a5573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124c99190614148565b516124e7576040516308148def60e11b815260040160405180910390fd5b60408051600280825260608201835290916020830190803683370190505060408051600280825260608201909252919450816020015b606081526020019060019003908161251d575050604080516002808252606082018352929450919060208301908036833701905050905087835f8151811061256757612567613e98565b6001600160a01b039092166020928302919091019091015260405163095ea7b360e01b9061259b90899089906024016141b5565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b038381831617835250505050825f815181106125e0576125e0613e98565b602002602001018190525083836001815181106125ff576125ff613e98565b6001600160a01b0390921660209283029190910190910152604051630efe6a8b60e01b90612635908a90899089906024016141ce565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b0383818316178352505050508260018151811061267b5761267b613e98565b60200260200101819052505b6040516370a0823160e01b81525f906001600160a01b038916906370a08231906126b5908d90600401613581565b602060405180830381865afa1580156126d0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126f49190613fae565b604051632f378c5f60e21b81529091506001600160a01b038b169063bcde317c9061272790879086908890600401614249565b5f604051808303815f87803b15801561273e575f5ffd5b505af1158015612750573d5f5f3e3d5ffd5b505050505f81896001600160a01b03166370a082318d6040518263ffffffff1660e01b81526004016127829190613581565b602060405180830381865afa15801561279d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127c19190613fae565b6127cb91906142db565b9050868110156127ee5760405163cea9e31d60e01b815260040160405180910390fd5b886001600160a01b03168a6001600160a01b03168c6001600160a01b03167f9f98725972b4a57ffe3d55d47002c227624652f061fa0498dc1aeb46e47e6cd68b85604051612846929190918252602082015260400190565b60405180910390a45050505050505050505050565b5f6128de7f855511cc3694f64379908437d6d64458dc76d02482052bfb8a5b33a72c054c77463061288b8c6130ea565b604080516001600160a01b03808f1660208301528d16918101919091526001600160801b03808c1660608301528a16608082015261ffff891660a082015262ffffff881660c08201528d9060e001611ff9565b98975050505050505050565b6001600160a01b038087165f90815260016020526040902054168061292257604051631d08fca760e11b815260040160405180910390fd5b846001600160801b03165f0361294b5760405163b4fa3fb360e01b815260040160405180910390fd5b61295f8888876001600160801b03166131ca565b60405163734d18e160e11b81526001600160a01b0387811660048301526001600160801b038716602483015261ffff851660448301525f919083169063e69a31c290606401602060405180830381865afa1580156129bf573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129e391906142fa565b9050846001600160801b0316816001600160801b03161015612a185760405163cea9e31d60e01b815260040160405180910390fd5b6040805160028082526060820183525f926020830190803683375050604080516002808252606082019092529293505f929150602082015b6060815260200190600190039081612a505750506040805160028082526060820183529293505f9290916020830190803683370190505090508a835f81518110612a9c57612a9c613e98565b6001600160a01b03928316602091820292909201015260405190861660248201526001600160801b038a16604482015263095ea7b360e01b90606401604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b038381831617835250505050825f81518110612b1d57612b1d613e98565b60200260200101819052508483600181518110612b3c57612b3c613e98565b6001600160a01b039283166020918202929092010152604051908b1660248201526001600160801b038a16604482015261ffff8816606482015262ffffff871660848201526335d9da3b60e11b9060a401604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b03838183161783525050505082600181518110612bd357612bd3613e98565b6020908102919091010152604051632f378c5f60e21b81526001600160a01b038d169063bcde317c90612c0e90869085908790600401614249565b5f604051808303815f87803b158015612c25575f5ffd5b505af1158015612c37573d5f5f3e3d5ffd5b505050508a6001600160a01b03168c6001600160a01b03167fcb39f8bb1228be3c7badb0539f9fa2f31dcdb4a60a5e83d8c4bcf543341d8dd68b87604051612c959291906001600160801b0392831681529116602082015260400190565b60405180910390a3505050505050505050505050565b5f6001600160601b03821115612ce3576040516306dfcc6560e41b815260606004820152602481018390526044015b60405180910390fd5b5090565b5f612db27f7360ecb005ef445b1cb2b3a294f2c499b088f258b4531fffbc4c244d8cf7732346308d6001600160a01b03166369615a4c6040518163ffffffff1660e01b81526004016020604051808303815f875af1158015612d4b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612d6f9190613fae565b8e8e8e8e8e604051602001611ff994939291906001600160a01b03948516815263ffffffff93909316602084015292166040820152606081019190915260800190565b60405163a732422d60e01b81529091506001600160a01b038b169063a732422d90612de9908490899089908990899060040161403c565b602060405180830381865afa158015612e04573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e289190613aa9565b612e455760405163274cf40160e01b815260040160405180910390fd5b50505050505050505050565b6001600160a01b0384161580612e65575080155b80612e7757506001600160a01b038216155b15612e955760405163b4fa3fb360e01b815260040160405180910390fd5b6001600160a01b038085165f908152602081905260409020541680612ecd5760405163f66d0cc960e01b815260040160405180910390fd5b604051635c463eed60e11b81526001600160a01b0387811660048301528681166024830152604482018490527f0000000000000000000000000000000000000000000000000000000000000000169063b88c7dda906064015f604051808303815f87803b158015612f3c575f5ffd5b505af1158015612f4e573d5f5f3e3d5ffd5b50506040805163ffffffff88168152602081018690526001600160a01b03808816945089811693508a16917f24e6075c9cd2aa1789761b7a7160092f3d7fabdd9acc044929f56009b2431ce2910160405180910390a45f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316636bc07b2b6040518163ffffffff1660e01b8152600401606060405180830381865afa158015613001573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130259190614315565b50509050806001600160401b03165f0361304b576130468787878787611beb565b6130da565b6040805160808101825263ffffffff80881682526001600160a01b03808a1660208085019182528486018981528a8416606087019081528e85165f908152600293849052979097209551865493518516600160201b026001600160c01b031990941695169490941791909117845591516001840155925191018054919092166001600160a01b03199091161790555b50505050505050565b80825d5050565b5f5f6130f4611b7e565b6001600160a01b039093165f90815260209390935250506040902080546001810190915590565b5f823b156131a457604051630b135d3f60e11b808252906001600160a01b03851690631626ba7e906131539088908790600401614355565b602060405180830381865afa15801561316e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613192919061436d565b6001600160e01b031916149050611b77565b826001600160a01b03166131b885846131f9565b6001600160a01b031614949350505050565b6131d48383613223565b8111156131f45760405163fe6beeaf60e01b815260040160405180910390fd5b505050565b5f5f5f5f6132078686613383565b92509250925061321782826133cc565b50909150505b92915050565b6040516364698e8360e11b81526001600160a01b03838116600483015282811660248301525f9182917f0000000000000000000000000000000000000000000000000000000000000000169063c8d31d0690604401602060405180830381865afa158015613293573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132b79190613fae565b90505f73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeed196001600160a01b038516016132f057506001600160a01b0384163161335e565b6040516370a0823160e01b81526001600160a01b038516906370a082319061331c908890600401613581565b602060405180830381865afa158015613337573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061335b9190613fae565b90505b80821115613370575f9250505061321d565b61337a82826142db565b95945050505050565b5f5f5f83516041036133ba576020840151604085015160608601515f1a6133ac88828585613484565b9550955095505050506133c5565b505081515f91506002905b9250925092565b5f8260038111156133df576133df614394565b036133e8575050565b60018260038111156133fc576133fc614394565b0361341a5760405163f645eedf60e01b815260040160405180910390fd5b600282600381111561342e5761342e614394565b0361344f5760405163fce698f760e01b815260048101829052602401612cda565b600382600381111561346357613463614394565b0361040d576040516335e2f38360e21b815260048101829052602401612cda565b5f80806fa2a8918ca85bafe22016d0b997e4df60600160ff1b038411156134b357505f91506003905082613538565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015613504573d5f5f3e3d5ffd5b5050604051601f1901519150506001600160a01b03811661352f57505f925060019150829050613538565b92505f91508190505b9450945094915050565b6001600160a01b0381168114610d73575f5ffd5b803561356181613542565b919050565b5f60208284031215613576575f5ffd5b8135611b7781613542565b6001600160a01b0391909116815260200190565b5f5f604083850312156135a6575f5ffd5b82356135b181613542565b915060208301356135c181613542565b809150509250929050565b5f5f83601f8401126135dc575f5ffd5b5081356001600160401b038111156135f2575f5ffd5b6020830191508360208260051b850101111561360c575f5ffd5b9250929050565b5f5f5f5f5f60608688031215613627575f5ffd5b853561363281613542565b945060208601356001600160401b0381111561364c575f5ffd5b613658888289016135cc565b90955093505060408601356001600160401b03811115613676575f5ffd5b613682888289016135cc565b969995985093965092949392505050565b5f5f83601f8401126136a3575f5ffd5b5081356001600160401b038111156136b9575f5ffd5b60208301915083602082850101111561360c575f5ffd5b5f5f5f5f5f5f5f5f60e0898b0312156136e7575f5ffd5b88356136f281613542565b9750602089013561370281613542565b9650604089013561371281613542565b9550606089013594506080890135935060a089013561373081613542565b925060c08901356001600160401b0381111561374a575f5ffd5b6137568b828c01613693565b999c989b5096995094979396929594505050565b6001600160801b0381168114610d73575f5ffd5b61ffff81168114610d73575f5ffd5b803562ffffff81168114613561575f5ffd5b5f5f5f5f5f5f5f5f5f5f6101208b8d0312156137b9575f5ffd5b8a356137c481613542565b995060208b01356137d481613542565b985060408b01356137e481613542565b975060608b01356137f48161376a565b965060808b01356138048161376a565b955060a08b01356138148161377e565b945061382260c08c0161378d565b935061383060e08c01613556565b92506101008b01356001600160401b0381111561384b575f5ffd5b6138578d828e01613693565b915080935050809150509295989b9194979a5092959850565b5f5f5f5f60408587031215613883575f5ffd5b84356001600160401b03811115613898575f5ffd5b6138a4878288016135cc565b90955093505060208501356001600160401b038111156138c2575f5ffd5b6138ce878288016135cc565b95989497509550505050565b5f5f602083850312156138eb575f5ffd5b82356001600160401b03811115613900575f5ffd5b61390c858286016135cc565b90969095509350505050565b5f5f60208385031215613929575f5ffd5b82356001600160401b0381111561393e575f5ffd5b61390c85828601613693565b803563ffffffff81168114613561575f5ffd5b5f5f5f5f60808587031215613970575f5ffd5b843561397b81613542565b93506139896020860161394a565b9250604085013561399981613542565b9396929550929360600135925050565b5f5f5f5f5f5f5f5f5f60e08a8c0312156139c1575f5ffd5b89356139cc81613542565b98506139da60208b0161394a565b975060408a01356139ea81613542565b965060608a0135955060808a0135613a0181613542565b945060a08a01356001600160401b03811115613a1b575f5ffd5b613a278c828d016135cc565b90955093505060c08a01356001600160401b03811115613a45575f5ffd5b613a518c828d016135cc565b915080935050809150509295985092959850929598565b5f60208284031215613a78575f5ffd5b8151611b7781613542565b9182526001600160a01b0316602082015260400190565b80518015158114613561575f5ffd5b5f60208284031215613ab9575f5ffd5b611b7782613a9a565b805161356181613542565b634e487b7160e01b5f52604160045260245ffd5b60405161016081016001600160401b0381118282101715613b0457613b04613acd565b60405290565b604051608081016001600160401b0381118282101715613b0457613b04613acd565b60405160c081016001600160401b0381118282101715613b0457613b04613acd565b604051601f8201601f191681016001600160401b0381118282101715613b7657613b76613acd565b604052919050565b80516001600160401b0381168114613561575f5ffd5b5f6101608284031215613ba5575f5ffd5b613bad613ae1565b825181526020808401519082015260408084015190820152606080840151908201526080808401519082015260a080840151908201529050613bf160c08301613b7e565b60c0820152613c0260e08301613b7e565b60e0820152613c146101008301613b7e565b610100820152613c276101208301613b7e565b6101208201526101409182015191810191909152919050565b5f6001600160401b03821115613c5857613c58613acd565b5060051b60200190565b5f82601f830112613c71575f5ffd5b8151613c84613c7f82613c40565b613b4e565b8082825260208201915060208360051b860101925085831115613ca5575f5ffd5b602085015b83811015613cc2578051835260209283019201613caa565b5095945050505050565b80516001600160601b0381168114613561575f5ffd5b5f60808284031215613cf2575f5ffd5b613cfa613b0a565b905081516001600160401b03811115613d11575f5ffd5b8201601f81018413613d21575f5ffd5b8051613d2f613c7f82613c40565b8082825260208201915060208360051b850101925086831115613d50575f5ffd5b6020840193505b82841015613d7b578351613d6a81613542565b825260209384019390910190613d57565b845250505060208201516001600160401b03811115613d98575f5ffd5b613da484828501613c62565b602083015250613db660408301613ac2565b6040820152613dc760608301613ccc565b606082015292915050565b805160028110613561575f5ffd5b5f60208284031215613df0575f5ffd5b81516001600160401b03811115613e05575f5ffd5b82016102008185031215613e17575f5ffd5b613e1f613b2c565b613e298583613b94565b81526101608201516001600160401b03811115613e44575f5ffd5b613e5086828501613ce2565b602083015250613e636101808301613dd2565b60408201526101a082015160608201526101c08201516080820152613e8b6101e08301613dd2565b60a0820152949350505050565b634e487b7160e01b5f52603260045260245ffd5b8183526020830192505f815f5b84811015613eea578135613ecc81613542565b6001600160a01b031686526020958601959190910190600101613eb9565b5093949350505050565b604081525f613f07604083018688613eac565b82810360208401526119f5818587613eac565b602081525f613f2d602083018486613eac565b949350505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160601b03851681526001600160a01b03841660208201526080604082018190525f90613f9590830185613f35565b905060018060a01b038316606083015295945050505050565b5f60208284031215613fbe575f5ffd5b5051919050565b6001600160601b03861681526001600160a01b038516602082015260a0604082018190525f90613ff790830186613f35565b6001600160a01b0394909416606083015250608001529392505050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b858152606060208201525f614055606083018688613eac565b8281036040840152838152602080820190600586901b830101865f36829003601e19015b888210156140e657858403601f190185528235818112614097575f5ffd5b8a016020810190356001600160401b038111156140b2575f5ffd5b8036038213156140c0575f5ffd5b6140cb868284614014565b95505050602083019250602085019450600182019150614079565b50919b9a5050505050505050505050565b86815260208082018790526001600160601b0319606087811b821660408501526054840187905285901b16607483015282515f9181908501608885015e5f9201608801918252509695505050505050565b5f6060828403128015614159575f5ffd5b50604051606081016001600160401b038111828210171561417c5761417c613acd565b60405261418883613a9a565b815261419660208401613a9a565b602082015260408301516141a98161377e565b60408201529392505050565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039390931683526020830191909152604082015260600190565b5f82825180855260208501945060208160051b830101602085015f5b8381101561423d57601f19858403018852614227838351613f35565b602098890198909350919091019060010161420b565b50909695505050505050565b606080825284519082018190525f9060208601906080840190835b8181101561428b5783516001600160a01b0316835260209384019390920191600101614264565b5050838103602080860191909152865180835291810192508601905f5b818110156142c65782518452602093840193909201916001016142a8565b505050828103604084015261201b81856141ef565b8181038181111561321d57634e487b7160e01b5f52601160045260245ffd5b5f6020828403121561430a575f5ffd5b8151611b778161376a565b5f5f5f60608486031215614327575f5ffd5b61433084613b7e565b925061433e60208501613b7e565b915061434c60408501613b7e565b90509250925092565b828152604060208201525f613f2d6040830184613f35565b5f6020828403121561437d575f5ffd5b81516001600160e01b031981168114611b77575f5ffd5b634e487b7160e01b5f52602160045260245ffdfe190e6e5b9101a41c1085c403f9d38fa1e0e3120692e46d71ff2bdc157986e1959b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00a164736f6c634300081c000a00000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000140000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a77800000000000000000000000053000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000005000000000000000000000000f0bb20865277abd641a307ece5ee04e79073416c0000000000000000000000005f46d540b6ed704c3c8789105f30e075aa90072600000000000000000000000008c6f91e2b681faf5e17227f2a44c307b3c1364c000000000000000000000000939778d83b46b456224a33fb59630b11dec56663000000000000000000000000657e8c867d8b37dcc18fa4caead9c45eb088c64200000000000000000000000000000000000000000000000000000000000000050000000000000000000000009aa79c84b79816ab920bbce20f8f74557b5147340000000000000000000000008ea0b382d054dbebeb1d0ae47ee4ac433c7303530000000000000000000000004de413a26fc24c3fc27cc983be70aa9c5c299387000000000000000000000000cc9a7620d0358a521a068b444846e3d5debea8fa0000000000000000000000006ee3aaccf9f2321e49063c4f8da775ddbd407268
Deployed Bytecode
0x60806040526004361061013f575f3560e01c806371e5dc81116100af57806371e5dc811461035b5780637c0691b31461037a5780638322fff2146103995780638a2e5c3d146103c0578063909030d5146103f35780639e673bc314610411578063a66e9d0a14610444578063b176806514610463578063c760e2ff14610496578063ceb5724714610575578063d17a613114610588578063d41f1771146105a7578063f9fba81b146105da575f5ffd5b80630a44077a146101435780631eb2b17e1461018d5780632b03a50c146101c45780632d0335ab146101e55780632db274c8146102125780633575f0de1461023157806339f1bc2c146102645780633fc8cef31461028457806343832054146102b75780635988e7a1146102eb57806360b72616146102fe57806363baa2601461031d578063709b0f511461033c575b5f5ffd5b34801561014e575f5ffd5b5061017761015d366004613566565b5f602081905290815260409020546001600160a01b031681565b6040516101849190613581565b60405180910390f35b348015610198575f5ffd5b506101776101a7366004613566565b6001600160a01b039081165f908152600160205260409020541690565b3480156101cf575f5ffd5b506101e36101de366004613595565b61060d565b005b3480156101f0575f5ffd5b506102046101ff366004613566565b610844565b604051908152602001610184565b34801561021d575f5ffd5b506101e361022c366004613566565b61086b565b34801561023c575f5ffd5b506101777f0000000000000000000000007ca0b75e67e33c0014325b739a8d019c4fe445f081565b34801561026f575f5ffd5b506102045f5160206143a95f395f51905f5281565b34801561028f575f5ffd5b506101777f000000000000000000000000530000000000000000000000000000000000000481565b3480156102c2575f5ffd5b506101776102d1366004613566565b60016020525f90815260409020546001600160a01b031681565b6101e36102f9366004613566565b610a32565b348015610309575f5ffd5b506101e3610318366004613613565b610d76565b348015610328575f5ffd5b506101e36103373660046136d0565b6110c4565b348015610347575f5ffd5b506101e361035636600461379f565b61122f565b348015610366575f5ffd5b506101e3610375366004613870565b6113a0565b348015610385575f5ffd5b506101e36103943660046138da565b611733565b3480156103a4575f5ffd5b5061017773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b3480156103cb575f5ffd5b506102047f6aa129b587db2f56b32662e4af4556cdc69b6228434cb2791c6377894b40bf2c81565b3480156103fe575f5ffd5b506101e361040d366004613918565b5050565b34801561041c575f5ffd5b506102047f7360ecb005ef445b1cb2b3a294f2c499b088f258b4531fffbc4c244d8cf7732381565b34801561044f575f5ffd5b5061020461045e36600461395d565b61190a565b34801561046e575f5ffd5b506102047f855511cc3694f64379908437d6d64458dc76d02482052bfb8a5b33a72c054c7781565b3480156104a1575f5ffd5b5061052d6104b0366004613566565b604080516080810182525f808252602082018190529181018290526060810191909152506001600160a01b039081165f908152600260208181526040928390208351608081018552815463ffffffff81168252600160201b9004861692810192909252600181015493820193909352910154909116606082015290565b6040516101849190815163ffffffff1681526020808301516001600160a01b039081169183019190915260408084015190830152606092830151169181019190915260800190565b6101e36105833660046139a9565b611a00565b348015610593575f5ffd5b506102046105a2366004613566565b611ae4565b3480156105b2575f5ffd5b506102047f48c73f681176fc7b3f9693986fd7b14581e8d540519e27400e88b8713932be0181565b3480156105e5575f5ffd5b506101777f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a77881565b7f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a7786001600160a01b03166308c732596040518163ffffffff1660e01b8152600401602060405180830381865afa158015610669573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061068d9190613a68565b6001600160a01b03166391d148545f5160206143a95f395f51905f52336040518363ffffffff1660e01b81526004016106c7929190613a83565b602060405180830381865afa1580156106e2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107069190613aa9565b610722576040516282b42960e81b815260040160405180910390fd5b6001600160a01b038216158061073f57506001600160a01b038116155b1561075d57604051632a9ffab760e21b815260040160405180910390fd5b806001600160a01b031663f3b977846040518163ffffffff1660e01b8152600401602060405180830381865afa158015610799573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107bd9190613a68565b6001600160a01b0316826001600160a01b0316146107ee576040516335c66c9960e01b815260040160405180910390fd5b6001600160a01b038281165f8181526001602052604080822080546001600160a01b0319169486169485179055517fdd001770b3f22fb8a32aee0705976d01646098f9c1254e8064d2ee09184490189190a35050565b5f61084d611b7e565b6001600160a01b039092165f90815260209290925250604090205490565b7f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a7786001600160a01b031663882d16986040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108c7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108eb9190613a68565b6001600160a01b0316336001600160a01b03161461091b576040516282b42960e81b815260040160405180910390fd5b6001600160a01b038082165f908152600260208181526040928390208351608081018552815463ffffffff81168252600160201b90048616928101929092526001810154938201939093529101549091166060820181905261097b575050565b80606001516001600160a01b031681602001516001600160a01b0316836001600160a01b03167f2e3c65d07c4fc7496e4f35bdc83c653debda281afe443cf6f2d2b0e4d02d6783845f015185604001516040516109ea92919063ffffffff929092168252602082015260400190565b60405180910390a4506001600160a01b03165f908152600260208190526040822080546001600160c01b031916815560018101929092550180546001600160a01b0319169055565b610a3a611ba2565b60405163b7ca418b60e01b815281906001600160a01b037f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a778169063b7ca418b90610a88908490600401613581565b602060405180830381865afa158015610aa3573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ac79190613aa9565b610ae4576040516334d0b49960e01b815260040160405180910390fd5b6001600160a01b038083165f908152600260208181526040928390208351608081018552815463ffffffff81168252600160201b900486169281019290925260018101549382019390935291015490911660608201819052610b5957604051638a88784960e01b815260040160405180910390fd5b604051631c13359160e11b81525f906001600160a01b037f0000000000000000000000007ca0b75e67e33c0014325b739a8d019c4fe445f016906338266b2290610ba7908790600401613581565b5f60405180830381865afa158015610bc1573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610be89190810190613de0565b6020015160408101519091506001600160a01b031630141580610c0e5750805151600114155b80610c4b575081602001516001600160a01b0316815f01515f81518110610c3757610c37613e98565b60200260200101516001600160a01b031614155b80610c775750816040015181602001515f81518110610c6c57610c6c613e98565b602002602001015114155b15610c955760405163a78fbb5f60e01b815260040160405180910390fd5b604051631e0d280960e11b81526001600160a01b037f0000000000000000000000007ca0b75e67e33c0014325b739a8d019c4fe445f01690633c1a501290610ce1908790600401613581565b5f604051808303815f87803b158015610cf8575f5ffd5b505af1158015610d0a573d5f5f3e3d5ffd5b50505050610d2a848360200151845f015185606001518660400151611beb565b5050506001600160a01b0381165f908152600260208190526040822080546001600160c01b031916815560018101929092550180546001600160a01b0319169055610d73611ddb565b50565b610d7e611ba2565b60405163b7ca418b60e01b815285906001600160a01b037f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a778169063b7ca418b90610dcc908490600401613581565b602060405180830381865afa158015610de7573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0b9190613aa9565b610e28576040516334d0b49960e01b815260040160405180910390fd5b610e358686868686611df2565b6001600160a01b038087165f908152600260208181526040928390208351608081018552815463ffffffff81168252600160201b900486169281019290925260018101549382019390935291015490911660608201819052610eaa57604051638a88784960e01b815260040160405180910390fd5b604051631c13359160e11b81525f906001600160a01b037f0000000000000000000000007ca0b75e67e33c0014325b739a8d019c4fe445f016906338266b2290610ef8908b90600401613581565b5f60405180830381865afa158015610f12573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610f399190810190613de0565b9050306001600160a01b03168160200151604001516001600160a01b031603610fd65760405163526cd20560e11b81526001600160a01b037f0000000000000000000000007ca0b75e67e33c0014325b739a8d019c4fe445f0169063a4d9a40a90610fa8908b90600401613581565b5f604051808303815f87803b158015610fbf575f5ffd5b505af1158015610fd1573d5f5f3e3d5ffd5b505050505b6001600160a01b038881165f90815260026020526040902054600160201b900416156110b25781606001516001600160a01b031682602001516001600160a01b0316896001600160a01b03167f2e3c65d07c4fc7496e4f35bdc83c653debda281afe443cf6f2d2b0e4d02d6783855f0151866040015160405161106b92919063ffffffff929092168252602082015260400190565b60405180910390a46001600160a01b0388165f908152600260208190526040822080546001600160c01b031916815560018101929092550180546001600160a01b03191690555b5050506110bd611ddb565b5050505050565b60405163b7ca418b60e01b815288906001600160a01b037f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a778169063b7ca418b90611112908490600401613581565b602060405180830381865afa15801561112d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111519190613aa9565b61116e576040516334d0b49960e01b815260040160405180910390fd5b8884816001600160a01b03166324d7806c826040518263ffffffff1660e01b815260040161119c9190613581565b602060405180830381865afa1580156111b7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111db9190613aa9565b6111f857604051632afafb8760e21b815260040160405180910390fd5b5f6112068c8c8c8c8c611f98565b905061121481888888612025565b6112218c8c8c8c8c61208b565b505050505050505050505050565b60405163b7ca418b60e01b81528a906001600160a01b037f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a778169063b7ca418b9061127d908490600401613581565b602060405180830381865afa158015611298573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112bc9190613aa9565b6112d9576040516334d0b49960e01b815260040160405180910390fd5b8a84816001600160a01b03166324d7806c826040518263ffffffff1660e01b81526004016113079190613581565b602060405180830381865afa158015611322573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113469190613aa9565b61136357604051632afafb8760e21b815260040160405180910390fd5b5f6113738e8e8e8e8e8e8e61285b565b905061138181888888612025565b6113908e8e8e8e8e8e8e6128ea565b5050505050505050505050505050565b7f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a7786001600160a01b03166308c732596040518163ffffffff1660e01b8152600401602060405180830381865afa1580156113fc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114209190613a68565b6001600160a01b03166391d148545f5160206143a95f395f51905f52336040518363ffffffff1660e01b815260040161145a929190613a83565b602060405180830381865afa158015611475573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114999190613aa9565b6114b5576040516282b42960e81b815260040160405180910390fd5b828181146114d65760405163512509d360e11b815260040160405180910390fd5b805f036114f65760405163b4fa3fb360e01b815260040160405180910390fd5b5f5b818110156116ee575f86868381811061151357611513613e98565b90506020020160208101906115289190613566565b6001600160a01b0316148061156b57505f84848381811061154b5761154b613e98565b90506020020160208101906115609190613566565b6001600160a01b0316145b156115895760405163b4fa3fb360e01b815260040160405180910390fd5b85858281811061159b5761159b613e98565b90506020020160208101906115b09190613566565b6001600160a01b03168484838181106115cb576115cb613e98565b90506020020160208101906115e09190613566565b6001600160a01b031663fbfa77cf6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561161b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061163f9190613a68565b6001600160a01b0316146116665760405163c52a9bd360e01b815260040160405180910390fd5b83838281811061167857611678613e98565b905060200201602081019061168d9190613566565b5f5f8888858181106116a1576116a1613e98565b90506020020160208101906116b69190613566565b6001600160a01b03908116825260208201929092526040015f2080546001600160a01b031916929091169190911790556001016114f8565b507feb3d2ee89a264650a8a29fb1c1be99f36ba69e616861cd44feb7cc77dca9fd53858585856040516117249493929190613ef4565b60405180910390a15050505050565b7f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a7786001600160a01b03166308c732596040518163ffffffff1660e01b8152600401602060405180830381865afa15801561178f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117b39190613a68565b6001600160a01b03166391d148545f5160206143a95f395f51905f52336040518363ffffffff1660e01b81526004016117ed929190613a83565b602060405180830381865afa158015611808573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061182c9190613aa9565b611848576040516282b42960e81b815260040160405180910390fd5b805f81900361186a5760405163b4fa3fb360e01b815260040160405180910390fd5b5f5b818110156118cb575f5f85858481811061188857611888613e98565b905060200201602081019061189d9190613566565b6001600160a01b0316815260208101919091526040015f2080546001600160a01b031916905560010161186c565b507f367cb6a9904bc3ce17bcf0727db772a2c5533312a93548f9714612928a9feeb483836040516118fd929190613f1a565b60405180910390a1505050565b6001600160a01b038085165f90815260208190526040812054909116806119445760405163f66d0cc960e01b815260040160405180910390fd5b6040805163ffffffff871660208201525f91016040516020818303038152906040529050816001600160a01b031663d7424e3361198086612cab565b878473eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6040518563ffffffff1660e01b81526004016119b69493929190613f63565b602060405180830381865afa1580156119d1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119f59190613fae565b979650505050505050565b611a08611ba2565b60405163b7ca418b60e01b815289906001600160a01b037f000000000000000000000000dc515cb479a64552c5a11a57109c314e40a1a778169063b7ca418b90611a56908490600401613581565b602060405180830381865afa158015611a71573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a959190613aa9565b611ab2576040516334d0b49960e01b815260040160405180910390fd5b611ac38a898b898b8a8a8a8a612ce7565b611ad08a898b898b612e51565b50611ad9611ddb565b505050505050505050565b6001600160a01b038082165f9081526002602081815260408084208151608081018352815463ffffffff81168252600160201b90048716938101939093526001810154918301919091529091015490921660608301819052909190611b5c57604051638a88784960e01b815260040160405180910390fd5b611b778160200151825f01518360600151846040015161190a565b9392505050565b7f9425b2e03e09da4c20ff7a465da264f7a02bf7079e1dbb47fce0436e1d206d0090565b5f5160206143c95f395f51905f525c15611bcf57604051633ee5aeb560e01b815260040160405180910390fd5b611be960015f5160206143c95f395f51905f525b906130e3565b565b6001600160a01b038085165f908152602081905260409020541680611c235760405163f66d0cc960e01b815260040160405180910390fd5b6040805163ffffffff861660208201525f910160405160208183030381529060405290505f826001600160a01b031663d7424e33611c6086612cab565b878573eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6040518563ffffffff1660e01b8152600401611c969493929190613f63565b602060405180830381865afa158015611cb1573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611cd59190613fae565b905080471015611cf857604051639c92bdfb60e01b815260040160405180910390fd5b826001600160a01b0316630592174082611d1187612cab565b888673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee876040518763ffffffff1660e01b8152600401611d49959493929190613fc5565b5f604051808303818588803b158015611d60575f5ffd5b505af1158015611d72573d5f5f3e3d5ffd5b50506040805163ffffffff8b168152602081018990529081018590526001600160a01b03808a1694508b811693508c1691507f089e0f7208f8fc06b9f41edffa576cac33d3135cb9f438dbb23abeebc96ea1949060600160405180910390a45050505050505050565b611be95f5f5160206143c95f395f51905f52611be3565b5f611efd7f6aa129b587db2f56b32662e4af4556cdc69b6228434cb2791c6377894b40bf2c4630896001600160a01b03166369615a4c6040518163ffffffff1660e01b81526004016020604051808303815f875af1158015611e56573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e7a9190613fae565b6040805160208101959095528401929092526001600160601b0319606091821b811682850152607484019290925289901b16609482015260a8015b604051602081830303815290604052805190602001207f19457468657265756d205369676e6564204d6573736167653a0a3332000000005f908152601c91909152603c902090565b60405163a732422d60e01b81529091506001600160a01b0387169063a732422d90611f34908490899089908990899060040161403c565b602060405180830381865afa158015611f4f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f739190613aa9565b611f905760405163274cf40160e01b815260040160405180910390fd5b505050505050565b5f61201b7f48c73f681176fc7b3f9693986fd7b14581e8d540519e27400e88b8713932be014630611fc88a6130ea565b604080516001600160a01b03808d1660208301528b169181019190915260608101899052608081018890528b9060a0015b60408051601f1981840301815290829052611eb59695949392916020016140f7565b9695505050505050565b6120688383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525089949392505061311b9050565b61208557604051638baa579f60e01b815260040160405180910390fd5b50505050565b6001600160a01b038084165f9081526020819052604090205416806120c35760405163f66d0cc960e01b815260040160405180910390fd5b8215806120ce575081155b156120ec5760405163b4fa3fb360e01b815260040160405180910390fd5b6120f78686856131ca565b6060808073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeed196001600160a01b0389160161245e576040516320ff722560e11b81526001600160a01b038516906341fee44a9061216c907f000000000000000000000000530000000000000000000000000000000000000490600401613581565b606060405180830381865afa158015612187573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121ab9190614148565b516121c9576040516308148def60e11b815260040160405180910390fd5b6040805160038082526080820190925290602082016060803683370190505060408051600380825260808201909252919450816020015b606081526020019060019003908161220057505060408051600380825260808201909252919350602082016060803683370190505090507f0000000000000000000000005300000000000000000000000000000000000004835f8151811061226a5761226a613e98565b6001600160a01b0390921660209283029190910182015260408051600481526024810190915290810180516001600160e01b0316630d0e30db60e41b179052825183905f906122bb576122bb613e98565b602002602001018190525085815f815181106122d9576122d9613e98565b6020026020010181815250507f00000000000000000000000053000000000000000000000000000000000000048360018151811061231957612319613e98565b6001600160a01b039092166020928302919091019091015260405163095ea7b360e01b9061234d90899089906024016141b5565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b0383818316178352505050508260018151811061239357612393613e98565b602002602001018190525083836002815181106123b2576123b2613e98565b6001600160a01b0390921660209283029190910190910152604051630efe6a8b60e01b90612408907f000000000000000000000000530000000000000000000000000000000000000490899089906024016141ce565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b0383818316178352505050508260028151811061244e5761244e613e98565b6020026020010181905250612687565b6040516320ff722560e11b81526001600160a01b038516906341fee44a9061248a908b90600401613581565b606060405180830381865afa1580156124a5573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124c99190614148565b516124e7576040516308148def60e11b815260040160405180910390fd5b60408051600280825260608201835290916020830190803683370190505060408051600280825260608201909252919450816020015b606081526020019060019003908161251d575050604080516002808252606082018352929450919060208301908036833701905050905087835f8151811061256757612567613e98565b6001600160a01b039092166020928302919091019091015260405163095ea7b360e01b9061259b90899089906024016141b5565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b038381831617835250505050825f815181106125e0576125e0613e98565b602002602001018190525083836001815181106125ff576125ff613e98565b6001600160a01b0390921660209283029190910190910152604051630efe6a8b60e01b90612635908a90899089906024016141ce565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b0383818316178352505050508260018151811061267b5761267b613e98565b60200260200101819052505b6040516370a0823160e01b81525f906001600160a01b038916906370a08231906126b5908d90600401613581565b602060405180830381865afa1580156126d0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126f49190613fae565b604051632f378c5f60e21b81529091506001600160a01b038b169063bcde317c9061272790879086908890600401614249565b5f604051808303815f87803b15801561273e575f5ffd5b505af1158015612750573d5f5f3e3d5ffd5b505050505f81896001600160a01b03166370a082318d6040518263ffffffff1660e01b81526004016127829190613581565b602060405180830381865afa15801561279d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127c19190613fae565b6127cb91906142db565b9050868110156127ee5760405163cea9e31d60e01b815260040160405180910390fd5b886001600160a01b03168a6001600160a01b03168c6001600160a01b03167f9f98725972b4a57ffe3d55d47002c227624652f061fa0498dc1aeb46e47e6cd68b85604051612846929190918252602082015260400190565b60405180910390a45050505050505050505050565b5f6128de7f855511cc3694f64379908437d6d64458dc76d02482052bfb8a5b33a72c054c77463061288b8c6130ea565b604080516001600160a01b03808f1660208301528d16918101919091526001600160801b03808c1660608301528a16608082015261ffff891660a082015262ffffff881660c08201528d9060e001611ff9565b98975050505050505050565b6001600160a01b038087165f90815260016020526040902054168061292257604051631d08fca760e11b815260040160405180910390fd5b846001600160801b03165f0361294b5760405163b4fa3fb360e01b815260040160405180910390fd5b61295f8888876001600160801b03166131ca565b60405163734d18e160e11b81526001600160a01b0387811660048301526001600160801b038716602483015261ffff851660448301525f919083169063e69a31c290606401602060405180830381865afa1580156129bf573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129e391906142fa565b9050846001600160801b0316816001600160801b03161015612a185760405163cea9e31d60e01b815260040160405180910390fd5b6040805160028082526060820183525f926020830190803683375050604080516002808252606082019092529293505f929150602082015b6060815260200190600190039081612a505750506040805160028082526060820183529293505f9290916020830190803683370190505090508a835f81518110612a9c57612a9c613e98565b6001600160a01b03928316602091820292909201015260405190861660248201526001600160801b038a16604482015263095ea7b360e01b90606401604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b038381831617835250505050825f81518110612b1d57612b1d613e98565b60200260200101819052508483600181518110612b3c57612b3c613e98565b6001600160a01b039283166020918202929092010152604051908b1660248201526001600160801b038a16604482015261ffff8816606482015262ffffff871660848201526335d9da3b60e11b9060a401604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b03838183161783525050505082600181518110612bd357612bd3613e98565b6020908102919091010152604051632f378c5f60e21b81526001600160a01b038d169063bcde317c90612c0e90869085908790600401614249565b5f604051808303815f87803b158015612c25575f5ffd5b505af1158015612c37573d5f5f3e3d5ffd5b505050508a6001600160a01b03168c6001600160a01b03167fcb39f8bb1228be3c7badb0539f9fa2f31dcdb4a60a5e83d8c4bcf543341d8dd68b87604051612c959291906001600160801b0392831681529116602082015260400190565b60405180910390a3505050505050505050505050565b5f6001600160601b03821115612ce3576040516306dfcc6560e41b815260606004820152602481018390526044015b60405180910390fd5b5090565b5f612db27f7360ecb005ef445b1cb2b3a294f2c499b088f258b4531fffbc4c244d8cf7732346308d6001600160a01b03166369615a4c6040518163ffffffff1660e01b81526004016020604051808303815f875af1158015612d4b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612d6f9190613fae565b8e8e8e8e8e604051602001611ff994939291906001600160a01b03948516815263ffffffff93909316602084015292166040820152606081019190915260800190565b60405163a732422d60e01b81529091506001600160a01b038b169063a732422d90612de9908490899089908990899060040161403c565b602060405180830381865afa158015612e04573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e289190613aa9565b612e455760405163274cf40160e01b815260040160405180910390fd5b50505050505050505050565b6001600160a01b0384161580612e65575080155b80612e7757506001600160a01b038216155b15612e955760405163b4fa3fb360e01b815260040160405180910390fd5b6001600160a01b038085165f908152602081905260409020541680612ecd5760405163f66d0cc960e01b815260040160405180910390fd5b604051635c463eed60e11b81526001600160a01b0387811660048301528681166024830152604482018490527f0000000000000000000000007ca0b75e67e33c0014325b739a8d019c4fe445f0169063b88c7dda906064015f604051808303815f87803b158015612f3c575f5ffd5b505af1158015612f4e573d5f5f3e3d5ffd5b50506040805163ffffffff88168152602081018690526001600160a01b03808816945089811693508a16917f24e6075c9cd2aa1789761b7a7160092f3d7fabdd9acc044929f56009b2431ce2910160405180910390a45f7f0000000000000000000000007ca0b75e67e33c0014325b739a8d019c4fe445f06001600160a01b0316636bc07b2b6040518163ffffffff1660e01b8152600401606060405180830381865afa158015613001573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130259190614315565b50509050806001600160401b03165f0361304b576130468787878787611beb565b6130da565b6040805160808101825263ffffffff80881682526001600160a01b03808a1660208085019182528486018981528a8416606087019081528e85165f908152600293849052979097209551865493518516600160201b026001600160c01b031990941695169490941791909117845591516001840155925191018054919092166001600160a01b03199091161790555b50505050505050565b80825d5050565b5f5f6130f4611b7e565b6001600160a01b039093165f90815260209390935250506040902080546001810190915590565b5f823b156131a457604051630b135d3f60e11b808252906001600160a01b03851690631626ba7e906131539088908790600401614355565b602060405180830381865afa15801561316e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613192919061436d565b6001600160e01b031916149050611b77565b826001600160a01b03166131b885846131f9565b6001600160a01b031614949350505050565b6131d48383613223565b8111156131f45760405163fe6beeaf60e01b815260040160405180910390fd5b505050565b5f5f5f5f6132078686613383565b92509250925061321782826133cc565b50909150505b92915050565b6040516364698e8360e11b81526001600160a01b03838116600483015282811660248301525f9182917f0000000000000000000000007ca0b75e67e33c0014325b739a8d019c4fe445f0169063c8d31d0690604401602060405180830381865afa158015613293573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132b79190613fae565b90505f73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeed196001600160a01b038516016132f057506001600160a01b0384163161335e565b6040516370a0823160e01b81526001600160a01b038516906370a082319061331c908890600401613581565b602060405180830381865afa158015613337573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061335b9190613fae565b90505b80821115613370575f9250505061321d565b61337a82826142db565b95945050505050565b5f5f5f83516041036133ba576020840151604085015160608601515f1a6133ac88828585613484565b9550955095505050506133c5565b505081515f91506002905b9250925092565b5f8260038111156133df576133df614394565b036133e8575050565b60018260038111156133fc576133fc614394565b0361341a5760405163f645eedf60e01b815260040160405180910390fd5b600282600381111561342e5761342e614394565b0361344f5760405163fce698f760e01b815260048101829052602401612cda565b600382600381111561346357613463614394565b0361040d576040516335e2f38360e21b815260048101829052602401612cda565b5f80806fa2a8918ca85bafe22016d0b997e4df60600160ff1b038411156134b357505f91506003905082613538565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015613504573d5f5f3e3d5ffd5b5050604051601f1901519150506001600160a01b03811661352f57505f925060019150829050613538565b92505f91508190505b9450945094915050565b6001600160a01b0381168114610d73575f5ffd5b803561356181613542565b919050565b5f60208284031215613576575f5ffd5b8135611b7781613542565b6001600160a01b0391909116815260200190565b5f5f604083850312156135a6575f5ffd5b82356135b181613542565b915060208301356135c181613542565b809150509250929050565b5f5f83601f8401126135dc575f5ffd5b5081356001600160401b038111156135f2575f5ffd5b6020830191508360208260051b850101111561360c575f5ffd5b9250929050565b5f5f5f5f5f60608688031215613627575f5ffd5b853561363281613542565b945060208601356001600160401b0381111561364c575f5ffd5b613658888289016135cc565b90955093505060408601356001600160401b03811115613676575f5ffd5b613682888289016135cc565b969995985093965092949392505050565b5f5f83601f8401126136a3575f5ffd5b5081356001600160401b038111156136b9575f5ffd5b60208301915083602082850101111561360c575f5ffd5b5f5f5f5f5f5f5f5f60e0898b0312156136e7575f5ffd5b88356136f281613542565b9750602089013561370281613542565b9650604089013561371281613542565b9550606089013594506080890135935060a089013561373081613542565b925060c08901356001600160401b0381111561374a575f5ffd5b6137568b828c01613693565b999c989b5096995094979396929594505050565b6001600160801b0381168114610d73575f5ffd5b61ffff81168114610d73575f5ffd5b803562ffffff81168114613561575f5ffd5b5f5f5f5f5f5f5f5f5f5f6101208b8d0312156137b9575f5ffd5b8a356137c481613542565b995060208b01356137d481613542565b985060408b01356137e481613542565b975060608b01356137f48161376a565b965060808b01356138048161376a565b955060a08b01356138148161377e565b945061382260c08c0161378d565b935061383060e08c01613556565b92506101008b01356001600160401b0381111561384b575f5ffd5b6138578d828e01613693565b915080935050809150509295989b9194979a5092959850565b5f5f5f5f60408587031215613883575f5ffd5b84356001600160401b03811115613898575f5ffd5b6138a4878288016135cc565b90955093505060208501356001600160401b038111156138c2575f5ffd5b6138ce878288016135cc565b95989497509550505050565b5f5f602083850312156138eb575f5ffd5b82356001600160401b03811115613900575f5ffd5b61390c858286016135cc565b90969095509350505050565b5f5f60208385031215613929575f5ffd5b82356001600160401b0381111561393e575f5ffd5b61390c85828601613693565b803563ffffffff81168114613561575f5ffd5b5f5f5f5f60808587031215613970575f5ffd5b843561397b81613542565b93506139896020860161394a565b9250604085013561399981613542565b9396929550929360600135925050565b5f5f5f5f5f5f5f5f5f60e08a8c0312156139c1575f5ffd5b89356139cc81613542565b98506139da60208b0161394a565b975060408a01356139ea81613542565b965060608a0135955060808a0135613a0181613542565b945060a08a01356001600160401b03811115613a1b575f5ffd5b613a278c828d016135cc565b90955093505060c08a01356001600160401b03811115613a45575f5ffd5b613a518c828d016135cc565b915080935050809150509295985092959850929598565b5f60208284031215613a78575f5ffd5b8151611b7781613542565b9182526001600160a01b0316602082015260400190565b80518015158114613561575f5ffd5b5f60208284031215613ab9575f5ffd5b611b7782613a9a565b805161356181613542565b634e487b7160e01b5f52604160045260245ffd5b60405161016081016001600160401b0381118282101715613b0457613b04613acd565b60405290565b604051608081016001600160401b0381118282101715613b0457613b04613acd565b60405160c081016001600160401b0381118282101715613b0457613b04613acd565b604051601f8201601f191681016001600160401b0381118282101715613b7657613b76613acd565b604052919050565b80516001600160401b0381168114613561575f5ffd5b5f6101608284031215613ba5575f5ffd5b613bad613ae1565b825181526020808401519082015260408084015190820152606080840151908201526080808401519082015260a080840151908201529050613bf160c08301613b7e565b60c0820152613c0260e08301613b7e565b60e0820152613c146101008301613b7e565b610100820152613c276101208301613b7e565b6101208201526101409182015191810191909152919050565b5f6001600160401b03821115613c5857613c58613acd565b5060051b60200190565b5f82601f830112613c71575f5ffd5b8151613c84613c7f82613c40565b613b4e565b8082825260208201915060208360051b860101925085831115613ca5575f5ffd5b602085015b83811015613cc2578051835260209283019201613caa565b5095945050505050565b80516001600160601b0381168114613561575f5ffd5b5f60808284031215613cf2575f5ffd5b613cfa613b0a565b905081516001600160401b03811115613d11575f5ffd5b8201601f81018413613d21575f5ffd5b8051613d2f613c7f82613c40565b8082825260208201915060208360051b850101925086831115613d50575f5ffd5b6020840193505b82841015613d7b578351613d6a81613542565b825260209384019390910190613d57565b845250505060208201516001600160401b03811115613d98575f5ffd5b613da484828501613c62565b602083015250613db660408301613ac2565b6040820152613dc760608301613ccc565b606082015292915050565b805160028110613561575f5ffd5b5f60208284031215613df0575f5ffd5b81516001600160401b03811115613e05575f5ffd5b82016102008185031215613e17575f5ffd5b613e1f613b2c565b613e298583613b94565b81526101608201516001600160401b03811115613e44575f5ffd5b613e5086828501613ce2565b602083015250613e636101808301613dd2565b60408201526101a082015160608201526101c08201516080820152613e8b6101e08301613dd2565b60a0820152949350505050565b634e487b7160e01b5f52603260045260245ffd5b8183526020830192505f815f5b84811015613eea578135613ecc81613542565b6001600160a01b031686526020958601959190910190600101613eb9565b5093949350505050565b604081525f613f07604083018688613eac565b82810360208401526119f5818587613eac565b602081525f613f2d602083018486613eac565b949350505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160601b03851681526001600160a01b03841660208201526080604082018190525f90613f9590830185613f35565b905060018060a01b038316606083015295945050505050565b5f60208284031215613fbe575f5ffd5b5051919050565b6001600160601b03861681526001600160a01b038516602082015260a0604082018190525f90613ff790830186613f35565b6001600160a01b0394909416606083015250608001529392505050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b858152606060208201525f614055606083018688613eac565b8281036040840152838152602080820190600586901b830101865f36829003601e19015b888210156140e657858403601f190185528235818112614097575f5ffd5b8a016020810190356001600160401b038111156140b2575f5ffd5b8036038213156140c0575f5ffd5b6140cb868284614014565b95505050602083019250602085019450600182019150614079565b50919b9a5050505050505050505050565b86815260208082018790526001600160601b0319606087811b821660408501526054840187905285901b16607483015282515f9181908501608885015e5f9201608801918252509695505050505050565b5f6060828403128015614159575f5ffd5b50604051606081016001600160401b038111828210171561417c5761417c613acd565b60405261418883613a9a565b815261419660208401613a9a565b602082015260408301516141a98161377e565b60408201529392505050565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039390931683526020830191909152604082015260600190565b5f82825180855260208501945060208160051b830101602085015f5b8381101561423d57601f19858403018852614227838351613f35565b602098890198909350919091019060010161420b565b50909695505050505050565b606080825284519082018190525f9060208601906080840190835b8181101561428b5783516001600160a01b0316835260209384019390920191600101614264565b5050838103602080860191909152865180835291810192508601905f5b818110156142c65782518452602093840193909201916001016142a8565b505050828103604084015261201b81856141ef565b8181038181111561321d57634e487b7160e01b5f52601160045260245ffd5b5f6020828403121561430a575f5ffd5b8151611b778161376a565b5f5f5f60608486031215614327575f5ffd5b61433084613b7e565b925061433e60208501613b7e565b915061434c60408501613b7e565b90509250925092565b828152604060208201525f613f2d6040830184613f35565b5f6020828403121561437d575f5ffd5b81516001600160e01b031981168114611b77575f5ffd5b634e487b7160e01b5f52602160045260245ffdfe190e6e5b9101a41c1085c403f9d38fa1e0e3120692e46d71ff2bdc157986e1959b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00a164736f6c634300081c000a
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.09
Net Worth in ETH
Token Allocations
ETH
100.00%
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|---|---|---|---|---|
| SCROLL | 100.00% | $2,868.17 | 0.00003026 | $0.086786 |
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.