Source Code
Overview
ETH Balance
0 ETH
Eth Value
$0.00| Transaction Hash |
Method
|
Block
|
From
|
|
To
|
||||
|---|---|---|---|---|---|---|---|---|---|
Latest 5 internal transactions
Advanced mode:
| Parent Transaction Hash | Method | Block |
From
|
|
To
|
||
|---|---|---|---|---|---|---|---|
| 0x60806040 | 24598892 | 2 hrs ago | Contract Creation | 0 ETH | |||
| 0x60a06040 | 24598892 | 2 hrs ago | Contract Creation | 0 ETH | |||
| 0x60806040 | 24591850 | 25 hrs ago | Contract Creation | 0 ETH | |||
| 0x60a06040 | 24591850 | 25 hrs ago | Contract Creation | 0 ETH | |||
| 0x60806040 | 23982729 | 86 days ago | Contract Creation | 0 ETH |
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Name:
FolioDeployer
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { IVotes } from "@openzeppelin/contracts/governance/utils/IVotes.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IFolioDeployer } from "@interfaces/IFolioDeployer.sol";
import { IGovernanceDeployer } from "@interfaces/IGovernanceDeployer.sol";
import { Folio, IFolio } from "@src/Folio.sol";
import { FolioProxyAdmin, FolioProxy } from "@folio/FolioProxy.sol";
import { AUCTION_LAUNCHER, BRAND_MANAGER, DEFAULT_ADMIN_ROLE, REBALANCE_MANAGER } from "@utils/Constants.sol";
import { Versioned } from "@utils/Versioned.sol";
/**
* @title Folio Deployer
* @author akshatmittal, julianmrodri, pmckelvy1, tbrent
*/
contract FolioDeployer is IFolioDeployer, Versioned {
address public immutable versionRegistry;
address public immutable daoFeeRegistry;
address public immutable trustedFillerRegistry;
address public immutable folioImplementation;
IGovernanceDeployer public immutable governanceDeployer;
constructor(
address _daoFeeRegistry,
address _versionRegistry,
address _trustedFillerRegistry,
IGovernanceDeployer _governanceDeployer
) {
daoFeeRegistry = _daoFeeRegistry;
versionRegistry = _versionRegistry;
trustedFillerRegistry = _trustedFillerRegistry;
folioImplementation = address(new Folio());
governanceDeployer = _governanceDeployer;
}
/// Deploy a raw Folio instance with previously defined roles
/// @return folio The deployed Folio instance
/// @return proxyAdmin The deployed FolioProxyAdmin instance
function deployFolio(
IFolio.FolioBasicDetails calldata basicDetails,
IFolio.FolioAdditionalDetails calldata additionalDetails,
IFolio.FolioFlags calldata folioFlags,
address owner,
address[] memory basketManagers,
address[] memory auctionLaunchers,
address[] memory brandManagers,
bytes32 deploymentNonce
) public returns (Folio folio, address proxyAdmin) {
require(basicDetails.assets.length == basicDetails.amounts.length, FolioDeployer__LengthMismatch());
bytes32 deploymentSalt = keccak256(
abi.encode(
msg.sender,
keccak256(
abi.encode(
basicDetails,
additionalDetails,
folioFlags,
owner,
basketManagers,
auctionLaunchers,
brandManagers
)
),
deploymentNonce
)
);
// Deploy Folio
proxyAdmin = address(new FolioProxyAdmin{ salt: deploymentSalt }(owner, versionRegistry));
folio = Folio(address(new FolioProxy{ salt: deploymentSalt }(folioImplementation, proxyAdmin)));
for (uint256 i; i < basicDetails.assets.length; i++) {
SafeERC20.safeTransferFrom(
IERC20(basicDetails.assets[i]),
msg.sender,
address(folio),
basicDetails.amounts[i]
);
}
folio.initialize(
basicDetails,
additionalDetails,
IFolio.FolioRegistryIndex({ daoFeeRegistry: daoFeeRegistry, trustedFillerRegistry: trustedFillerRegistry }),
folioFlags,
msg.sender
);
// Setup Roles
folio.grantRole(folio.DEFAULT_ADMIN_ROLE(), owner);
for (uint256 i; i < basketManagers.length; i++) {
folio.grantRole(REBALANCE_MANAGER, basketManagers[i]);
}
for (uint256 i; i < auctionLaunchers.length; i++) {
folio.grantRole(AUCTION_LAUNCHER, auctionLaunchers[i]);
}
for (uint256 i; i < brandManagers.length; i++) {
folio.grantRole(BRAND_MANAGER, brandManagers[i]);
}
// Renounce Ownership
if (owner != address(this)) {
folio.renounceRole(folio.DEFAULT_ADMIN_ROLE(), address(this));
}
emit FolioDeployed(owner, address(folio), proxyAdmin);
}
// internal-only struct for stack-too-deep
struct GovernancePair {
address governor;
address timelock;
}
/// Deploy a Folio instance with brand new owner + trading governors
/// @param stToken The staking vault for the staking token, pass address(0) to self-govern
/// @param ownerGovParams Re-used for stToken when self-governed
/// @param govRoles.existingBasketManagers Pass empty array to deploy a trading governor
/// @return folio The deployed Folio instance
/// @return proxyAdmin The deployed FolioProxyAdmin instance
function deployGovernedFolio(
IVotes stToken,
IFolio.FolioBasicDetails calldata basicDetails,
IFolio.FolioAdditionalDetails calldata additionalDetails,
IFolio.FolioFlags calldata folioFlags,
IGovernanceDeployer.GovParams calldata ownerGovParams,
IGovernanceDeployer.GovParams calldata tradingGovParams,
GovRoles calldata govRoles,
bytes32 deploymentNonce
) external returns (Folio folio, address proxyAdmin) {
bytes32 deploymentSalt = keccak256(abi.encode(msg.sender, deploymentNonce));
// Deploy Folio
(folio, proxyAdmin) = deployFolio(
basicDetails,
additionalDetails,
folioFlags,
address(this), // temporary owner
govRoles.existingBasketManagers,
govRoles.auctionLaunchers,
govRoles.brandManagers,
deploymentSalt
);
GovernancePair[] memory govPairs = new GovernancePair[](2);
// govPairs[0] is owner governor
// govPairs[1] is trading governor
if (address(stToken) == address(0)) {
// Self-govern
(stToken, govPairs[0].governor, govPairs[0].timelock) = governanceDeployer.deployGovernedStakingToken(
string(abi.encodePacked("Vote-Locked ", basicDetails.name)),
string(abi.encodePacked("VL", basicDetails.symbol)),
folio,
ownerGovParams,
deploymentSalt
);
} else {
// Deploy separate owner governance
(govPairs[0].governor, govPairs[0].timelock) = governanceDeployer.deployGovernanceWithTimelock(
ownerGovParams,
stToken,
deploymentSalt
);
}
// Deploy trading Governance if basket managers are not provided
if (govRoles.existingBasketManagers.length == 0) {
// Invert deployment nonce to avoid timelock/governor collisions
(govPairs[1].governor, govPairs[1].timelock) = governanceDeployer.deployGovernanceWithTimelock(
tradingGovParams,
stToken,
~deploymentSalt
);
folio.grantRole(REBALANCE_MANAGER, govPairs[1].timelock);
}
// Swap Folio owner
folio.grantRole(DEFAULT_ADMIN_ROLE, govPairs[0].timelock);
folio.renounceRole(DEFAULT_ADMIN_ROLE, address(this));
// Swap proxyAdmin owner
FolioProxyAdmin(payable(proxyAdmin)).transferOwnership(govPairs[0].timelock);
emit GovernedFolioDeployed(
address(stToken),
address(folio),
govPairs[0].governor,
govPairs[0].timelock,
govPairs[1].governor,
govPairs[1].timelock
);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.20;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*/
interface IVotes {
/**
* @dev The signature used has expired.
*/
error VotesExpiredSignature(uint256 expiry);
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of voting units.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousVotes, uint256 newVotes);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
* configured to use block numbers, this will return the value at the end of the corresponding block.
*/
function getPastVotes(address account, uint256 timepoint) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
* configured to use block numbers, this will return the value at the end of the corresponding block.
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 timepoint) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IFolioDeployer {
error FolioDeployer__LengthMismatch();
event FolioDeployed(address indexed folioOwner, address indexed folio, address folioAdmin);
event GovernedFolioDeployed(
address indexed stToken,
address indexed folio,
address ownerGovernor,
address ownerTimelock,
address tradingGovernor,
address tradingTimelock
);
struct GovRoles {
address[] existingBasketManagers;
address[] auctionLaunchers;
address[] brandManagers;
}
function folioImplementation() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IVotes } from "@openzeppelin/contracts/governance/utils/IVotes.sol";
import { StakingVault } from "@staking/StakingVault.sol";
interface IGovernanceDeployer {
struct GovParams {
// Basic Parameters
uint48 votingDelay; // {s}
uint32 votingPeriod; // {s}
uint256 proposalThreshold; // D18{1}
uint256 quorumThreshold; // D18{1}
uint256 timelockDelay; // {s}
// Roles
address[] guardians; // Canceller Role
}
function deployGovernedStakingToken(
string memory name,
string memory symbol,
IERC20 underlying,
IGovernanceDeployer.GovParams calldata govParams,
bytes32 deploymentNonce
) external returns (StakingVault stToken, address governor, address timelock);
function deployGovernanceWithTimelock(
IGovernanceDeployer.GovParams calldata govParams,
IVotes stToken,
bytes32 deploymentNonce
) external returns (address governor, address timelock);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol";
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { ITrustedFillerRegistry, IBaseTrustedFiller } from "@reserve-protocol/trusted-fillers/contracts/interfaces/ITrustedFillerRegistry.sol";
import { RebalancingLib } from "@utils/RebalancingLib.sol";
import { AUCTION_WARMUP, AUCTION_LAUNCHER, D18, D27, ERC20_STORAGE_LOCATION, REBALANCE_MANAGER, MAX_TVL_FEE, MAX_MINT_FEE, MIN_MINT_FEE, MIN_AUCTION_LENGTH, MAX_AUCTION_LENGTH, MAX_FEE_RECIPIENTS, RESTRICTED_AUCTION_BUFFER, ONE_OVER_YEAR, ONE_DAY } from "@utils/Constants.sol";
import { MathLib } from "@utils/MathLib.sol";
import { Versioned } from "@utils/Versioned.sol";
import { IFolioDAOFeeRegistry } from "@interfaces/IFolioDAOFeeRegistry.sol";
import { IFolio } from "@interfaces/IFolio.sol";
/**
* @title Folio
* @author akshatmittal, julianmrodri, pmckelvy1, tbrent
* @notice Folio is a backed ERC20 token with permissionless minting/redemption and a semi-permissioned rebalancing
* mechanism intended for rebalancing under timelock delay.
*
* A Folio is backed by a flexible number of ERC20 tokens of any denomination/price (within assumed ranges, see README)
* All tokens tracked by the Folio are required to mint/redeem. This forms the basket.
*
* There are 3 main roles:
* 1. DEFAULT_ADMIN_ROLE: can set erc20 assets, fees, auction length, close auctions/rebalances, and deprecateFolio
* 2. REBALANCE_MANAGER: can start/end rebalances, and end individual auctions
* 3. AUCTION_LAUNCHER: can open auctions and end rebalances/auctions
*
* There is also an additional BRAND_MANAGER role that does not have any permissions. It is for off-chain use.
*
* AUCTION_LAUNCHER assumptions:
* - SHOULD NOT close auctions/rebalances to deny the rebalance dishonestly
* - SHOULD craft auctions against progressively narrowed BU limits to responsibly DCA into the new basket
* - SHOULD end the ongoing rebalance when prices have moved outside the initially-provided price ranges
* - if weightControl=true: SHOULD progressively narrow weight ranges to maintain the original rebalance intent
* - if priceControl=PARTIAL: SHOULD provide narrowed price ranges that still include the current clearing price
* priceControl=ATOMIC_SWAP: SHOULD fill auction atomically directly after opening AND end rebalance after
*
* Rebalance lifecycle:
* startRebalance() -> openAuction()/openAuctionUnrestricted() -> bid()/createTrustedFill() -> [optional] closeAuction()
*
* After a new rebalance is started by the REBALANCE_MANAGER, there is a period of time where only the AUCTION_LAUNCHER
* can run auctions. They can specify a few different things:
* - The list of tokens to include in the auction; must be a subset of the tokens in the rebalance
* - Basket weight ranges: can progressively tighten the basket weight ranges, without backtracking
* - Individual token price ranges: can be a subset of the initially-provided range, if priceControl!=NONE
* - Rebalance limits: can progressively tighten the BU limits, without backtracking
*
* The AUCTION_LAUNCHER can run as many auctions as they need to. If they are close to the end of their restricted
* period the period will be extended automatically until a period of non-use occurs. However, they cannot extend the
* period indefinitely past the rebalance's end time. The final auction may extend past the rebalance's endTime, however.
*
* After the AUCTION_LAUNCHER's restricted period is over, anyone can open auctions until the rebalance expires. The
* AUCTION_LAUNCHER can always deny the unrestricted period by ending the rebalance when they are done.
*
* The unrestricted period exists primarily to avoid strong reliance on the AUCTION_LAUNCHER. The auctionLength should be
* long enough to support the price ranges provided by REBALANCE_MANAGER without excessive loss due to block precision
* in the case the AUCTION_LAUNCHER is not active.
*
* Auctions have a 30s delay at-start before bidding begins in order to ensure competition from the first block. This delay
* is bypassed in the priceControl=ATOMIC_SWAP case when startPrices are equal to endPrices.
*
* An auction for a set of tokens runs in parallel on all possible pairs simultaneously. The current price for each
* pair is interpolated along an exponential decay curve between their most-optimistic and most-pessimistic price
* estimates as a function of how much time in the auction has passed.
*
* In order for a pair to be eligible for an auction, the sell token must be in surplus and the buy token in deficit,
* as defined by balances relative to the (i) surplus: high weight * high BU limit; and (ii) deficit: low weight *
* low basket limit. Individual token weights can also be used to handle rebalancing independent of BU limits
* when the ideal relative ratios of token units is not known ahead of time.
*
* A Basket Unit {BU} can be defined within a (0, 1e27] range, but the typical usage defines BUs 1:1 with shares (1e18).
*
* Fees:
* - TVL fee: fee per unit time. Max 10% annually. Causes supply inflation over time, discretely once a day.
* - Mint fee: fee on mint. Max 5%. Does not cause supply inflation.
*
* After fees have been applied, the DAO takes a cut based on the configuration of the FolioDAOFeeRegistry including
* a minimum fee floor of 15bps. The remaining portion above 15bps is distributed to the Folio's fee recipients.
* Note that this means it is possible for the fee recipients to receive nothing despite configuring a nonzero fee.
*/
contract Folio is
IFolio,
Initializable,
ERC20Upgradeable,
AccessControlEnumerableUpgradeable,
ReentrancyGuardUpgradeable,
Versioned
{
using EnumerableSet for EnumerableSet.AddressSet;
/**
* Roles
*
* bytes32 constant REBALANCE_MANAGER = keccak256("REBALANCE_MANAGER"); // expected to be trading governance's timelock
* bytes32 constant AUCTION_LAUNCHER = keccak256("AUCTION_LAUNCHER"); // optional: EOA or multisig
* bytes32 constant BRAND_MANAGER = keccak256("BRAND_MANAGER"); // optional: no permissions
*/
IFolioDAOFeeRegistry public daoFeeRegistry;
/**
* Mandate
*/
string public mandate; // mutable field that describes mission/brand of the Folio
/**
* Basket
*/
EnumerableSet.AddressSet private basket;
/**
* Fees
*/
FeeRecipient[] public feeRecipients;
uint256 public tvlFee; // D18{1/s} demurrage fee on AUM
uint256 public mintFee; // D18{1} fee on mint
/**
* System
*/
uint256 public lastPoke; // {s}
uint256 public daoPendingFeeShares; // {share} shares pending to be distributed ONLY to the DAO
uint256 public feeRecipientsPendingFeeShares; // {share} shares pending to be distributed ONLY to fee recipients
bool public isDeprecated; // {bool} if true, Folio goes into redemption-only mode
modifier notDeprecated() {
require(!isDeprecated, Folio__FolioDeprecated());
_;
}
DeprecatedStruct[] private auctions_DEPRECATED;
mapping(address token => uint256 timepoint) private sellEnds_DEPRECATED;
mapping(address token => uint256 timepoint) private buyEnds_DEPRECATED;
uint256 private auctionDelay_DEPRECATED;
uint256 public auctionLength; // {s} length of an auction
// === 2.0.0 ===
mapping(uint256 auctionId => DeprecatedStruct details) private auctionDetails_DEPRECATED;
mapping(address token => uint256 amount) private dustAmount_DEPRECATED;
// === 3.0.0 ===
ITrustedFillerRegistry public trustedFillerRegistry;
bool public trustedFillerEnabled;
IBaseTrustedFiller private activeTrustedFill;
// === 4.0.0 ===
// 3.0.0 release was skipped so strict 3.0.0 -> 4.0.0 storage compatibility is not a requirement
RebalanceControl public rebalanceControl; // AUCTION_LAUNCHER control over rebalancing
/**
* Rebalancing
* REBALANCE_MANAGER
* - There can be any number of auctions within a rebalance, but only one live at a time
* - Auctions are restricted to the AUCTION_LAUNCHER until rebalance.restrictedUntil, with possible extensions
* - Auctions cannot be launched after availableUntil, though their start/end times may extend past it
* - Each auction the AUCTION_LAUNCHER provides: (i) basket limits; (i) weight ranges; and (iii) prices
* - Depending on the WeightControl, the AUCTION_LAUNCHER may be able to narrow weight ranges within the initial range
* - Depending on the PriceControl, the AUCTION_LAUNCHER may be able to narrow prices within the initial range
* - At anytime the rebalance can be stopped or a new one can be started. In the stopping case, any ongoing auction
* is able to continue completion, but in the restart case the ongoing auction is closed.
*/
Rebalance private rebalance;
/**
* Auctions
* Openable by AUCTION_LAUNCHER -> Openable by anyone (optional) -> Warmup (30s) -> Running -> Closed
* - An auction is in parallel on all surplus/deficit token pairs at the same time
* - Bids are of any size, up to a maximum given by the high/low basket limits and high/low token weights
* - All auctions are dutch auctions with an exponential decay curve between two points
* - The warmup period is bypassed in the priceControl=ATOMIC_SWAP case when startPrices are equal to endPrices
*/
mapping(uint256 id => Auction auction) public auctions;
uint256 public nextAuctionId;
// === 5.0.0 ===
bool public bidsEnabled;
/// Any external call to the Folio that relies on accurate share accounting must pre-hook poke
modifier sync() {
_poke();
_;
}
// ====
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
FolioBasicDetails calldata _basicDetails,
FolioAdditionalDetails calldata _additionalDetails,
FolioRegistryIndex calldata _folioRegistries,
FolioFlags calldata _folioFlags,
address _creator
) external initializer {
__ERC20_init(_basicDetails.name, _basicDetails.symbol);
__AccessControlEnumerable_init();
__AccessControl_init();
__ReentrancyGuard_init();
_setFeeRecipients(_additionalDetails.feeRecipients);
_setTVLFee(_additionalDetails.tvlFee);
_setMintFee(_additionalDetails.mintFee);
_setAuctionLength(_additionalDetails.auctionLength);
_setMandate(_additionalDetails.mandate);
_setRebalanceControl(_folioFlags.rebalanceControl);
_setBidsEnabled(_folioFlags.bidsEnabled);
_setTrustedFillerRegistry(_folioRegistries.trustedFillerRegistry, _folioFlags.trustedFillerEnabled);
_setDaoFeeRegistry(_folioRegistries.daoFeeRegistry);
require(_basicDetails.initialShares != 0, Folio__ZeroInitialShares());
uint256 assetLength = _basicDetails.assets.length;
require(assetLength != 0, Folio__EmptyAssets());
for (uint256 i; i < assetLength; i++) {
require(_basicDetails.assets[i] != address(0), Folio__InvalidAsset());
uint256 assetBalance = IERC20(_basicDetails.assets[i]).balanceOf(address(this));
require(assetBalance != 0, Folio__InvalidAssetAmount(_basicDetails.assets[i]));
_addToBasket(_basicDetails.assets[i]);
}
lastPoke = block.timestamp;
_mint(_creator, _basicDetails.initialShares);
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function poke() external nonReentrant {
_poke();
}
/// Check if the Folio state can be relied upon to be complete
/// @dev Safety check for consuming protocols to check for synchronous and asynchronous state changes
/// @dev Consuming protocols SHOULD call this function and ensure it returns (false, false) before
/// strongly relying on the Folio state. The asyncStateChangeActive check can be DoS'd for the current block.
function stateChangeActive() external view returns (bool syncStateChangeActive, bool asyncStateChangeActive) {
syncStateChangeActive = _reentrancyGuardEntered();
asyncStateChangeActive = address(activeTrustedFill) != address(0) && activeTrustedFill.swapActive();
}
// ==== Governance ====
/// Escape hatch function to be used when tokens get acquired not through an auction but
/// through any other means and should become part of the Folio without being sold.
/// @dev Does not require a token balance, hence can be backrun with removeFromBasket. Token
/// balance is highly recommended.
/// @param token The token to add to the basket
function addToBasket(IERC20 token) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
require(_addToBasket(address(token)), Folio__BasketModificationFailed());
}
/// @dev Enables permissionless removal of tokens for 0 balance tokens
function removeFromBasket(IERC20 token) external nonReentrant {
_closeTrustedFill();
// always allow admin to remove from basket
// allow permissionless removal if 0 weight AND 0 balance
// known: can be griefed by token donation
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) ||
(rebalance.details[address(token)].weights.spot == 0 && IERC20(token).balanceOf(address(this)) == 0),
Folio__BalanceNotRemovable()
);
require(_removeFromBasket(address(token)), Folio__BasketModificationFailed());
}
/// An annual tvl fee below the DAO fee floor will result in the entirety of the fee being sent to the DAO
/// @dev Non-reentrant via distributeFees()
/// @param _newFee D18{1/s} Fee per second on AUM
function setTVLFee(uint256 _newFee) external onlyRole(DEFAULT_ADMIN_ROLE) {
distributeFees();
_setTVLFee(_newFee);
}
/// A minting fee below the DAO fee floor will result in the entirety of the fee being sent to the DAO
/// @dev Non-reentrant via distributeFees()
/// @param _newFee D18{1} Fee on mint
function setMintFee(uint256 _newFee) external onlyRole(DEFAULT_ADMIN_ROLE) {
distributeFees();
_setMintFee(_newFee);
}
/// @dev Non-reentrant via distributeFees()
/// @dev Fee recipients must be unique and sorted by address, and sum to 1e18
/// @dev Warning: An empty fee recipients table will result in all fees being sent to DAO
function setFeeRecipients(FeeRecipient[] calldata _newRecipients) external onlyRole(DEFAULT_ADMIN_ROLE) {
distributeFees();
_setFeeRecipients(_newRecipients);
}
/// @param _newLength {s} Length of an auction
function setAuctionLength(uint256 _newLength) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
_setAuctionLength(_newLength);
}
/// @param _newMandate New mandate, a schelling point to guide governance
function setMandate(string calldata _newMandate) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setMandate(_newMandate);
}
/// @param _newName New token name
function setName(string calldata _newName) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setName(_newName);
}
/// @dev _newFillerRegistry must be the already set registry if already set. This is to ensure
/// correctness and in order to be explicit what registry is being enabled/disabled.
function setTrustedFillerRegistry(address _newFillerRegistry, bool _enabled) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setTrustedFillerRegistry(_newFillerRegistry, _enabled);
}
/// @dev Does not impact ongoing rebalances
/// @param _rebalanceControl.weightControl If AUCTION_LAUNCHER can move weights
/// @param _rebalanceControl.priceControl How the AUCTION_LAUNCHER can manipulate prices, if at all
function setRebalanceControl(RebalanceControl calldata _rebalanceControl) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setRebalanceControl(_rebalanceControl);
}
/// @param _bidsEnabled If true, permissionless bids are enabled
function setBidsEnabled(bool _bidsEnabled) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setBidsEnabled(_bidsEnabled);
}
/// Deprecate the Folio, callable only by the admin
/// @dev Folio cannot be minted and auctions cannot be approved, opened, or bid on
function deprecateFolio() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
isDeprecated = true;
emit FolioDeprecated();
}
// ==== Share + Asset Accounting ====
/// @dev Contains all pending fee shares
function totalSupply() public view override returns (uint256) {
(uint256 _daoPendingFeeShares, uint256 _feeRecipientsPendingFeeShares, ) = _getPendingFeeShares();
return super.totalSupply() + _daoPendingFeeShares + _feeRecipientsPendingFeeShares;
}
/// @dev Result may be unreliable mid-swap during trusted fill execution, check stateChangeActive()
/// @return _assets
/// @return _amounts {tok}
function totalAssets() external view returns (address[] memory _assets, uint256[] memory _amounts) {
return _totalAssets();
}
/// @dev Result may be unreliable mid-swap during trusted fill execution, check stateChangeActive()
/// @param shares {share}
/// @return _assets
/// @return _amounts {tok}
function toAssets(
uint256 shares,
Math.Rounding rounding
) external view returns (address[] memory _assets, uint256[] memory _amounts) {
return _toAssets(shares, rounding);
}
/// @dev Use allowances to set slippage limits for provided assets
/// @dev Minting has 3 share-portions: (i) receiver shares, (ii) DAO fee shares, (iii) fee recipients shares
/// @param shares {share} Amount of shares to mint
/// @param minSharesOut {share} Minimum amount of shares the caller must receive after fees
/// @return _assets
/// @return _amounts {tok}
function mint(
uint256 shares,
address receiver,
uint256 minSharesOut
) external nonReentrant notDeprecated sync returns (address[] memory _assets, uint256[] memory _amounts) {
// === Calculate fee shares ===
(, uint256 daoFeeNumerator, uint256 daoFeeDenominator, uint256 daoFeeFloor) = daoFeeRegistry.getFeeDetails(
address(this)
);
// ensure DAO fee floor is at least 3 bps (set just above daily MAX_TVL_FEE)
daoFeeFloor = Math.max(daoFeeFloor, MIN_MINT_FEE);
// {share} = {share} * D18{1} / D18
uint256 totalFeeShares = (shares * mintFee + D18 - 1) / D18;
uint256 daoFeeShares = (totalFeeShares * daoFeeNumerator + daoFeeDenominator - 1) / daoFeeDenominator;
// ensure DAO's portion of fees is at least the DAO feeFloor
uint256 minDaoShares = (shares * daoFeeFloor + D18 - 1) / D18;
daoFeeShares = daoFeeShares < minDaoShares ? minDaoShares : daoFeeShares;
// 100% to DAO, if necessary
totalFeeShares = totalFeeShares < daoFeeShares ? daoFeeShares : totalFeeShares;
// {share}
uint256 sharesOut = shares - totalFeeShares;
require(sharesOut != 0 && sharesOut >= minSharesOut, Folio__InsufficientSharesOut());
// === Transfer assets in ===
(_assets, _amounts) = _toAssets(shares, Math.Rounding.Ceil);
uint256 assetLength = _assets.length;
for (uint256 i; i < assetLength; i++) {
if (_amounts[i] != 0) {
SafeERC20.safeTransferFrom(IERC20(_assets[i]), msg.sender, address(this), _amounts[i]);
}
}
// === Mint shares ===
_mint(receiver, sharesOut);
// defer fee handouts until distributeFees()
daoPendingFeeShares += daoFeeShares;
feeRecipientsPendingFeeShares += totalFeeShares - daoFeeShares;
}
/// @param shares {share} Amount of shares to redeem
/// @param assets Assets to receive, must match basket exactly
/// @param minAmountsOut {tok} Minimum amounts of each asset to receive
/// @return _amounts {tok} Actual amounts transferred of each asset
function redeem(
uint256 shares,
address receiver,
address[] calldata assets,
uint256[] calldata minAmountsOut
) external nonReentrant sync returns (uint256[] memory _amounts) {
address[] memory _assets;
(_assets, _amounts) = _toAssets(shares, Math.Rounding.Floor);
// === Burn shares ===
_burn(msg.sender, shares);
// === Transfer assets out ===
uint256 len = _assets.length;
require(len == assets.length && len == minAmountsOut.length, Folio__InvalidArrayLengths());
for (uint256 i; i < len; i++) {
require(_assets[i] == assets[i], Folio__InvalidAsset());
require(_amounts[i] >= minAmountsOut[i], Folio__InvalidAssetAmount(_assets[i]));
if (_amounts[i] != 0) {
SafeERC20.safeTransfer(IERC20(_assets[i]), receiver, _amounts[i]);
}
}
}
// ==== Fee Shares ====
/// @return {share} Up-to-date sum of DAO and fee recipients pending fee shares
function getPendingFeeShares() public view returns (uint256) {
(uint256 _daoPendingFeeShares, uint256 _feeRecipientsPendingFeeShares, ) = _getPendingFeeShares();
return _daoPendingFeeShares + _feeRecipientsPendingFeeShares;
}
/// Distribute all pending fee shares
/// @dev Recipients: DAO and fee recipients; if feeRecipients are empty, the DAO gets all the fees
/// @dev Pending fee shares are already reflected in the total supply, this function only concretizes balances
function distributeFees() public nonReentrant sync {
// daoPendingFeeShares and feeRecipientsPendingFeeShares are up-to-date
// === Fee recipients ===
uint256 _feeRecipientsPendingFeeShares = feeRecipientsPendingFeeShares;
feeRecipientsPendingFeeShares = 0;
uint256 feeRecipientsTotal;
uint256 len = feeRecipients.length;
for (uint256 i; i < len; i++) {
// {share} = {share} * D18{1} / D18
uint256 shares = (_feeRecipientsPendingFeeShares * feeRecipients[i].portion) / D18;
feeRecipientsTotal += shares;
_mint(feeRecipients[i].recipient, shares);
emit FolioFeePaid(feeRecipients[i].recipient, shares);
}
// === DAO ===
// {share}
uint256 daoShares = daoPendingFeeShares + _feeRecipientsPendingFeeShares - feeRecipientsTotal;
(address daoRecipient, , , ) = daoFeeRegistry.getFeeDetails(address(this));
_mint(daoRecipient, daoShares);
emit ProtocolFeePaid(daoRecipient, daoShares);
daoPendingFeeShares = 0;
}
// ==== Auctions ====
/// Get the price of a token in an auction
function getAuctionPrice(uint256 auctionId, address token) external view returns (PriceRange memory range) {
range = auctions[auctionId].prices[token];
require(range.low != 0, Folio__InvalidAsset());
}
/// @dev stack-too-deep
struct RebalanceTimestamps {
uint256 startedAt; // {s} timestamp rebalancing started, inclusive
uint256 restrictedUntil; // {s} timestamp rebalancing becomes unrestricted, exclusive
uint256 availableUntil; // {s} timestamp rebalancing ends overall, exclusive
}
/// Get the currently ongoing rebalance
/// @dev Nonzero return values do not imply a rebalance is ongoing; check `rebalance.availableUntil`
/// @return nonce The current rebalance nonce
/// @return priceControl How much price control the AUCTION_LAUNCHER has: [NONE, PARTIAL, ATOMIC_SWAP]
/// @return tokens The rebalance parameters for each token in the basket
/// @return limits D18{BU/share} The current target limits for rebalancing
/// @return timestamps {s} The timestamps for the rebalance
/// @return bidsEnabled_ If true, permissionless bids are enabled for this rebalance
function getRebalance()
external
view
returns (
uint256 nonce,
PriceControl priceControl,
TokenRebalanceParams[] memory tokens,
RebalanceLimits memory limits,
RebalanceTimestamps memory timestamps,
bool bidsEnabled_
)
{
nonce = rebalance.nonce;
priceControl = rebalance.priceControl;
address[] memory basketTokens = basket.values();
uint256 len = basketTokens.length;
tokens = new TokenRebalanceParams[](len);
for (uint256 i; i < len; i++) {
address token = basketTokens[i];
RebalanceDetails storage details = rebalance.details[token];
tokens[i] = TokenRebalanceParams({
token: token,
weight: details.weights,
price: details.initialPrices,
maxAuctionSize: details.maxAuctionSize,
inRebalance: details.inRebalance
});
}
limits = rebalance.limits;
timestamps = RebalanceTimestamps({
startedAt: rebalance.startedAt,
restrictedUntil: rebalance.restrictedUntil,
availableUntil: rebalance.availableUntil
});
bidsEnabled_ = rebalance.bidsEnabled;
}
/// Start a new rebalance, ending the currently running auction
/// @dev If caller omits old tokens they will be kept in the basket for mint/redeem but skipped in the rebalance
/// @dev Note that weights will be _slightly_ stale after the fee supply inflation on a 24h boundary
/// @param tokens The rebalance parameters for each token in the rebalance
/// @param tokens.token MUST be unique
/// @param tokens.weight D27{tok/BU} Basket weight ranges; cannot be empty [0, 1e54]
/// @param tokens.price D27{UoA/tok} Prices for each token; cannot be empty (0, 1e45]
/// @param tokens.maxAuctionSize {tok} Max amount to sell in any single auction
/// @param tokens.inRebalance MUST be true
/// @param limits D18{BU/share} Target number of baskets should have at end of rebalance (0, 1e27]
/// @param auctionLauncherWindow {s} The amount of time the AUCTION_LAUNCHER has to open auctions, can be extended
/// @param ttl {s} The amount of time the rebalance is valid for
function startRebalance(
TokenRebalanceParams[] calldata tokens,
RebalanceLimits calldata limits,
uint256 auctionLauncherWindow,
uint256 ttl
) external onlyRole(REBALANCE_MANAGER) nonReentrant notDeprecated sync {
RebalancingLib.startRebalance(
basket.values(),
rebalanceControl,
rebalance,
tokens,
limits,
auctionLauncherWindow,
ttl,
bidsEnabled
);
// add new tokens to basket
for (uint256 i; i < tokens.length; i++) {
_addToBasket(tokens[i].token);
}
}
/// Open an auction as the AUCTION_LAUNCHER aimed at specific BU limits and weights, for a given set of tokens
/// @param rebalanceNonce The nonce of the rebalance being targeted
/// @param tokens The tokens from the rebalance to include in the auction; must be unique
/// @param newWeights D27{tok/BU} New basket weight ranges for BU definition; must always be provided
/// @param newPrices D27{UoA/tok} New price ranges; must always be provided and obey PriceControl setting
/// @param newLimits D18{BU/share} New BU limits; must be within range
/// @return auctionId The newly created auctionId
function openAuction(
uint256 rebalanceNonce,
address[] calldata tokens,
WeightRange[] calldata newWeights,
PriceRange[] calldata newPrices,
RebalanceLimits calldata newLimits
) external onlyRole(AUCTION_LAUNCHER) nonReentrant notDeprecated sync returns (uint256 auctionId) {
// require tokens are in the rebalance
uint256 len = tokens.length;
for (uint256 i; i < len; i++) {
require(rebalance.details[tokens[i]].inRebalance, Folio__InvalidAsset());
}
// open an auction on the provided limits, weights, and prices
auctionId = _openAuction(rebalanceNonce, tokens, newWeights, newPrices, newLimits, 0);
// bump rebalance deadlines to ensure an opportunity for the AUCTION_LAUNCHER to act again
// can potentially send the rebalance from the unrestricted period back into the restricted period
rebalance.restrictedUntil = Math.max(
rebalance.restrictedUntil,
block.timestamp + auctionLength + AUCTION_WARMUP + RESTRICTED_AUCTION_BUFFER + 1
);
}
/// Open an auction without caller restrictions, on all tokens in the rebalance on spot values and initial prices
/// @dev Callable only after the auction launcher window passes, and when no other auction is ongoing
/// @return auctionId The newly created auctionId
function openAuctionUnrestricted(
uint256 rebalanceNonce
) external nonReentrant notDeprecated sync returns (uint256 auctionId) {
require(block.timestamp >= rebalance.restrictedUntil, Folio__AuctionCannotBeOpenedWithoutRestriction());
address[] memory basketTokens = basket.values();
uint256 len = basketTokens.length;
// count tokens in rebalance
uint256 count;
for (uint256 i; i < len; i++) {
if (rebalance.details[basketTokens[i]].inRebalance) {
count++;
}
}
address[] memory tokens = new address[](count);
WeightRange[] memory weights = new WeightRange[](count);
PriceRange[] memory prices = new PriceRange[](count);
// use spot weights and initialPrices, collapsing high/low weight range
count = 0;
for (uint256 i; i < len; i++) {
RebalanceDetails storage rebalanceDetails = rebalance.details[basketTokens[i]];
if (rebalanceDetails.inRebalance) {
tokens[count] = basketTokens[i];
weights[count] = WeightRange({
low: rebalanceDetails.weights.spot,
spot: rebalanceDetails.weights.spot,
high: rebalanceDetails.weights.spot
});
prices[count] = rebalanceDetails.initialPrices;
count++;
}
}
// use spot limits, collapse high/low range
RebalanceLimits memory limits = RebalanceLimits({
low: rebalance.limits.spot,
spot: rebalance.limits.spot,
high: rebalance.limits.spot
});
// open an auction on spot limits, spot weights, and initial prices
auctionId = _openAuction(rebalanceNonce, tokens, weights, prices, limits, RESTRICTED_AUCTION_BUFFER);
}
/// Get auction bid parameters for an ongoing auction in the current block, for some token pair
/// @dev Result may be unreliable mid-swap during trusted fill execution, check stateChangeActive()
/// @param sellToken The token to sell
/// @param buyToken The token to buy
/// @param maxSellAmount {sellTok} The max amount of sell tokens the bidder is willing to buy
/// @return sellAmount {sellTok} The amount of sell token on sale in the auction at a given timestamp
/// @return bidAmount {buyTok} The amount of buy tokens required to bid for the full sell amount
/// @return price D27{buyTok/sellTok} The price at the given timestamp as an 27-decimal fixed point
function getBid(
uint256 auctionId,
IERC20 sellToken,
IERC20 buyToken,
uint256 maxSellAmount
) external view returns (uint256 sellAmount, uint256 bidAmount, uint256 price) {
return _getBid(auctions[auctionId], sellToken, buyToken, 0, maxSellAmount, type(uint256).max);
}
/// Bid in an ongoing auction
/// If withCallback is true, caller must adhere to IBidderCallee interface and receives a callback
/// If withCallback is false, caller must have provided an allowance in advance
/// @dev Callable by anyone
/// @param sellAmount {sellTok} Sell token, the token the bidder receives
/// @param maxBuyAmount {buyTok} Max buy token, the token the bidder provides
/// @param withCallback If true, caller must adhere to IBidderCallee interface and transfers tokens via callback
/// @param data Arbitrary data to pass to the callback
/// @return boughtAmt {buyTok} The amount the bidder pays
function bid(
uint256 auctionId,
IERC20 sellToken,
IERC20 buyToken,
uint256 sellAmount,
uint256 maxBuyAmount,
bool withCallback,
bytes calldata data
) external nonReentrant notDeprecated sync returns (uint256 boughtAmt) {
require(rebalance.bidsEnabled, Folio__PermissionlessBidsDisabled());
Auction storage auction = auctions[auctionId];
// checks auction is ongoing and that boughtAmt is below maxBuyAmount
(, boughtAmt, ) = _getBid(auction, sellToken, buyToken, sellAmount, sellAmount, maxBuyAmount);
// bid via approval or callback
if (RebalancingLib.bid(auction, auctionId, sellToken, buyToken, sellAmount, boughtAmt, withCallback, data)) {
_removeFromBasket(address(sellToken));
}
}
/// As an alternative to bidding directly, an in-block async swap can be opened without removing Folio's access
function createTrustedFill(
uint256 auctionId,
IERC20 sellToken,
IERC20 buyToken,
address targetFiller,
bytes32 deploymentSalt
) external nonReentrant notDeprecated sync returns (IBaseTrustedFiller filler) {
require(
address(trustedFillerRegistry) != address(0) && trustedFillerEnabled,
Folio__TrustedFillerRegistryNotEnabled()
);
// checks auction is ongoing
(uint256 sellAmount, uint256 buyAmount, ) = _getBid(
auctions[auctionId],
sellToken,
buyToken,
0,
type(uint256).max,
type(uint256).max
);
require(buyAmount != 0, Folio__InsufficientBuyAvailable());
// Create Trusted Filler
filler = trustedFillerRegistry.createTrustedFiller(msg.sender, targetFiller, deploymentSalt);
SafeERC20.forceApprove(sellToken, address(filler), sellAmount);
filler.initialize(address(this), sellToken, buyToken, sellAmount, buyAmount);
activeTrustedFill = filler;
emit AuctionTrustedFillCreated(auctionId, address(filler));
}
/// Close an auction
/// A auction can be closed from anywhere in its lifecycle
/// If you close an auction before startTime, it would break the invariant that endTime > startTime.
/// @dev Callable by ADMIN or REBALANCE_MANAGER or AUCTION_LAUNCHER
function closeAuction(uint256 auctionId) external nonReentrant {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) ||
hasRole(REBALANCE_MANAGER, msg.sender) ||
hasRole(AUCTION_LAUNCHER, msg.sender),
Folio__Unauthorized()
);
if (auctions[auctionId].endTime < block.timestamp) {
return;
}
// do not revert, to prevent griefing
auctions[auctionId].endTime = block.timestamp - 1; // inclusive
emit AuctionClosed(auctionId);
}
/// End the current rebalance, WITHOUT impacting any ongoing auction
/// @dev Callable by ADMIN or REBALANCE_MANAGER or AUCTION_LAUNCHER
function endRebalance() external nonReentrant {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) ||
hasRole(REBALANCE_MANAGER, msg.sender) ||
hasRole(AUCTION_LAUNCHER, msg.sender),
Folio__Unauthorized()
);
emit RebalanceEnded(rebalance.nonce);
// do not revert, to prevent griefing
rebalance.availableUntil = block.timestamp; // exclusive
}
// ==== Internal ====
/// @param shares {share}
/// @return _assets
/// @return _amounts {tok}
function _toAssets(
uint256 shares,
Math.Rounding rounding
) internal view returns (address[] memory _assets, uint256[] memory _amounts) {
uint256 _totalSupply = totalSupply();
(_assets, _amounts) = _totalAssets();
uint256 assetLen = _assets.length;
for (uint256 i; i < assetLen; i++) {
// {tok} = {share} * {tok} / {share}
_amounts[i] = Math.mulDiv(shares, _amounts[i], _totalSupply, rounding);
}
}
/// @return _assets
/// @return _amounts {tok}
function _totalAssets() internal view returns (address[] memory _assets, uint256[] memory _amounts) {
_assets = basket.values();
uint256 assetLength = _assets.length;
_amounts = new uint256[](assetLength);
for (uint256 i; i < assetLength; i++) {
_amounts[i] = _balanceOfToken(IERC20(_assets[i]));
}
}
/// @return amount The known balances of a token, including trusted fills
function _balanceOfToken(IERC20 token) internal view returns (uint256 amount) {
amount = token.balanceOf(address(this));
if (
address(activeTrustedFill) != address(0) &&
(activeTrustedFill.sellToken() == token || activeTrustedFill.buyToken() == token)
) {
amount += token.balanceOf(address(activeTrustedFill));
}
}
/// Open an auction
/// @param rebalanceNonce The nonce of the rebalance being targeted
/// @param tokens The tokens from the rebalance to include in the auction
/// @param limits D18{BU/share} The BU limits for the auction
/// @param auctionBuffer {s} The amount of extra buffer time to pad starting and ending rebalances/auctions
/// @return auctionId The newly created auctionId
function _openAuction(
uint256 rebalanceNonce,
address[] memory tokens,
WeightRange[] memory weights,
PriceRange[] memory prices,
RebalanceLimits memory limits,
uint256 auctionBuffer
) internal returns (uint256 auctionId) {
// enforce rebalance ongoing
require(
rebalance.nonce == rebalanceNonce &&
block.timestamp >= rebalance.startedAt + auctionBuffer &&
block.timestamp < rebalance.availableUntil,
Folio__NotRebalancing()
);
auctionId = nextAuctionId != 0 ? nextAuctionId : auctions_DEPRECATED.length;
nextAuctionId = auctionId + 1;
// close any previous auction
if (auctionId != 0) {
Auction storage lastAuction = auctions[auctionId - 1];
// if auction collision
if (
lastAuction.rebalanceNonce == rebalanceNonce && lastAuction.endTime + auctionBuffer >= block.timestamp
) {
require(auctionBuffer == 0, Folio__AuctionCannotBeOpenedWithoutRestriction());
// close ongoing auction
lastAuction.endTime = block.timestamp - 1;
emit AuctionClosed(auctionId - 1);
}
}
RebalancingLib.openAuction(rebalance, auctions, auctionId, tokens, weights, prices, limits, auctionLength);
}
/// Get auction bid parameters for a token pair at the current timestamp, up to a maximum sell amount
/// @param sellToken The token to sell
/// @param buyToken The token to buy
/// @param maxSellAmount {sellTok} The max amount of sell tokens the bidder is willing to buy
/// @return sellAmount {sellTok} The amount of sell token on sale in the auction at the given timestamp
/// @return bidAmount {buyTok} The amount of buy tokens required to bid for the full sell amount
/// @return price D27{buyTok/sellTok} The price at the given timestamp as an 27-decimal fixed point
function _getBid(
Auction storage auction,
IERC20 sellToken,
IERC20 buyToken,
uint256 minSellAmount,
uint256 maxSellAmount,
uint256 maxBuyAmount
) internal view returns (uint256 sellAmount, uint256 bidAmount, uint256 price) {
RebalancingLib.GetBidParams memory params = RebalancingLib.GetBidParams({
totalSupply: totalSupply(),
sellBal: _balanceOfToken(sellToken),
buyBal: _balanceOfToken(buyToken),
minSellAmount: minSellAmount,
maxSellAmount: maxSellAmount,
maxBuyAmount: maxBuyAmount
});
// checks auction is ongoing and that sellAmount is below maxSellAmount
(sellAmount, bidAmount, price) = RebalancingLib.getBid(rebalance, auction, sellToken, buyToken, params);
}
/// @return _daoPendingFeeShares {share}
/// @return _feeRecipientsPendingFeeShares {share}
function _getPendingFeeShares()
internal
view
returns (uint256 _daoPendingFeeShares, uint256 _feeRecipientsPendingFeeShares, uint256 _accountedUntil)
{
// {s} Always in full days
_accountedUntil = (block.timestamp / ONE_DAY) * ONE_DAY;
uint256 elapsed = _accountedUntil > lastPoke ? _accountedUntil - lastPoke : 0;
if (elapsed == 0) {
return (daoPendingFeeShares, feeRecipientsPendingFeeShares, lastPoke);
}
_daoPendingFeeShares = daoPendingFeeShares;
_feeRecipientsPendingFeeShares = feeRecipientsPendingFeeShares;
// {share}
uint256 supply = super.totalSupply() + _daoPendingFeeShares + _feeRecipientsPendingFeeShares;
(, uint256 daoFeeNumerator, uint256 daoFeeDenominator, uint256 daoFeeFloor) = daoFeeRegistry.getFeeDetails(
address(this)
);
// convert annual percentage to per-second for comparison with stored tvlFee
// = 1 - (1 - feeFloor) ^ (1 / 31536000)
// D18{1/s} = D18{1} - D18{1} * D18{1} ^ D18{1/s}
uint256 feeFloor = D18 - MathLib.pow(D18 - daoFeeFloor, ONE_OVER_YEAR);
// D18{1/s}
uint256 _tvlFee = feeFloor > tvlFee ? feeFloor : tvlFee;
// {share} += {share} * D18 / D18{1/s} ^ {s} - {share}
uint256 feeShares = (supply * D18) / MathLib.powu(D18 - _tvlFee, elapsed) - supply;
// D18{1} = D18{1/s} * D18 / D18{1/s}
uint256 correction = (feeFloor * D18 + _tvlFee - 1) / _tvlFee;
// {share} = {share} * D18{1} / D18
uint256 daoShares = (correction > (daoFeeNumerator * D18 + daoFeeDenominator - 1) / daoFeeDenominator)
? (feeShares * correction + D18 - 1) / D18
: (feeShares * daoFeeNumerator + daoFeeDenominator - 1) / daoFeeDenominator;
_daoPendingFeeShares += daoShares;
_feeRecipientsPendingFeeShares += feeShares - daoShares;
}
/// Set TVL fee by annual percentage. Different from how it is stored!
/// @param _newFeeAnnually D18{1}
function _setTVLFee(uint256 _newFeeAnnually) internal {
require(_newFeeAnnually <= MAX_TVL_FEE, Folio__TVLFeeTooHigh());
// convert annual percentage to per-second
// = 1 - (1 - _newFeeAnnually) ^ (1 / 31536000)
// D18{1/s} = D18{1} - D18{1} ^ {s}
tvlFee = D18 - MathLib.pow(D18 - _newFeeAnnually, ONE_OVER_YEAR);
require(_newFeeAnnually == 0 || tvlFee != 0, Folio__TVLFeeTooLow());
emit TVLFeeSet(tvlFee, _newFeeAnnually);
}
/// Set mint fee
/// @param _newFee D18{1}
function _setMintFee(uint256 _newFee) internal {
require(_newFee <= MAX_MINT_FEE, Folio__MintFeeTooHigh());
mintFee = _newFee;
emit MintFeeSet(_newFee);
}
/// @dev Warning: An empty fee recipients table will result in all fees being sent to DAO
function _setFeeRecipients(FeeRecipient[] calldata _feeRecipients) internal {
emit FeeRecipientsSet(_feeRecipients);
// Clear existing fee table
uint256 len = feeRecipients.length;
for (uint256 i; i < len; i++) {
feeRecipients.pop();
}
// Add new items to the fee table
len = _feeRecipients.length;
if (len == 0) {
return;
}
require(len <= MAX_FEE_RECIPIENTS, Folio__TooManyFeeRecipients());
address previousRecipient;
uint256 total;
for (uint256 i; i < len; i++) {
require(_feeRecipients[i].recipient > previousRecipient, Folio__FeeRecipientInvalidAddress());
require(_feeRecipients[i].portion != 0, Folio__FeeRecipientInvalidFeeShare());
total += _feeRecipients[i].portion;
previousRecipient = _feeRecipients[i].recipient;
feeRecipients.push(_feeRecipients[i]);
}
// ensure table adds up to 100%
require(total == D18, Folio__BadFeeTotal());
}
/// @param _newLength {s}
function _setAuctionLength(uint256 _newLength) internal {
require(_newLength >= MIN_AUCTION_LENGTH && _newLength <= MAX_AUCTION_LENGTH, Folio__InvalidAuctionLength());
auctionLength = _newLength;
emit AuctionLengthSet(auctionLength);
}
function _setMandate(string calldata _newMandate) internal {
mandate = _newMandate;
emit MandateSet(_newMandate);
}
/// @param _newName New token name
function _setName(string calldata _newName) internal {
ERC20Storage storage $;
assembly {
$.slot := ERC20_STORAGE_LOCATION
}
$._name = _newName;
emit NameSet(_newName);
}
/// @dev After: daoPendingFeeShares and feeRecipientsPendingFeeShares are up-to-date
function _poke() internal {
_closeTrustedFill();
(
uint256 _daoPendingFeeShares,
uint256 _feeRecipientsPendingFeeShares,
uint256 _accountedUntil
) = _getPendingFeeShares();
if (_accountedUntil > lastPoke) {
daoPendingFeeShares = _daoPendingFeeShares;
feeRecipientsPendingFeeShares = _feeRecipientsPendingFeeShares;
lastPoke = _accountedUntil;
}
}
function _addToBasket(address token) internal returns (bool) {
require(token != address(0) && token != address(this), Folio__InvalidAsset());
emit BasketTokenAdded(token);
return basket.add(token);
}
function _removeFromBasket(address token) internal returns (bool) {
emit BasketTokenRemoved(token);
delete rebalance.details[token];
return basket.remove(token);
}
function _setTrustedFillerRegistry(address _newFillerRegistry, bool _enabled) internal {
if (address(trustedFillerRegistry) != _newFillerRegistry) {
require(address(trustedFillerRegistry) == address(0), Folio__TrustedFillerRegistryAlreadySet());
trustedFillerRegistry = ITrustedFillerRegistry(_newFillerRegistry);
}
if (trustedFillerEnabled != _enabled) {
trustedFillerEnabled = _enabled;
}
emit TrustedFillerRegistrySet(address(trustedFillerRegistry), trustedFillerEnabled);
}
function _setRebalanceControl(RebalanceControl calldata _rebalanceControl) internal {
rebalanceControl = _rebalanceControl;
emit RebalanceControlSet(_rebalanceControl);
}
function _setBidsEnabled(bool _bidsEnabled) internal {
bidsEnabled = _bidsEnabled;
emit BidsEnabledSet(_bidsEnabled);
}
function _setDaoFeeRegistry(address _newDaoFeeRegistry) internal {
require(_newDaoFeeRegistry != address(0), Folio__InvalidRegistry());
daoFeeRegistry = IFolioDAOFeeRegistry(_newDaoFeeRegistry);
}
/// Claim all token balances from outstanding trusted fill
function _closeTrustedFill() internal {
if (address(activeTrustedFill) != address(0)) {
RebalancingLib.closeTrustedFill(auctions[nextAuctionId - 1], activeTrustedFill);
delete activeTrustedFill;
}
}
function _update(address from, address to, uint256 value) internal override {
// prevent accidental donations
require(to != address(this), Folio__InvalidTransferToSelf());
// balances acquired prior to 4.0.0 may still reside at the contract
super._update(from, to, value);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { ITransparentUpgradeableProxy } from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import { ERC1967Proxy, ERC1967Utils } from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IFolioVersionRegistry } from "@interfaces/IFolioVersionRegistry.sol";
/**
* @title FolioProxyAdmin
* @author akshatmittal, julianmrodri, pmckelvy1, tbrent
*/
contract FolioProxyAdmin is Ownable {
address public immutable versionRegistry;
error VersionDeprecated();
error InvalidVersion();
constructor(address initialOwner, address _versionRegistry) Ownable(initialOwner) {
versionRegistry = _versionRegistry;
}
function upgradeToVersion(address proxyTarget, bytes32 versionHash, bytes memory data) external onlyOwner {
IFolioVersionRegistry folioRegistry = IFolioVersionRegistry(versionRegistry);
require(!folioRegistry.isDeprecated(versionHash), VersionDeprecated());
require(address(folioRegistry.deployments(versionHash)) != address(0), InvalidVersion());
address folioImpl = folioRegistry.getImplementationForVersion(versionHash);
ITransparentUpgradeableProxy(proxyTarget).upgradeToAndCall(folioImpl, data);
}
}
/**
* @title FolioProxy
* @author akshatmittal, julianmrodri, pmckelvy1, tbrent
* @dev This is an alternate implementation of the TransparentUpgradeableProxy contract, please read through
* their considerations and limitations before using this contract.
*/
contract FolioProxy is ERC1967Proxy {
error ProxyDeniedAdminAccess();
constructor(address _logic, address _admin) ERC1967Proxy(_logic, "") {
/**
* @dev _admin must be proxyAdmin
* @notice Yes, admin can be an immutable variable. Doing this way to honor ERC1967 spec.
*/
ERC1967Utils.changeAdmin(_admin);
}
function _fallback() internal virtual override {
if (msg.sender == ERC1967Utils.getAdmin()) {
require(msg.sig == ITransparentUpgradeableProxy.upgradeToAndCall.selector, ProxyDeniedAdminAccess());
(address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} else {
super._fallback();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
uint256 constant AUCTION_WARMUP = 30; // {s} 30 seconds
uint256 constant MAX_TVL_FEE = 0.1e18; // D18{1/year} 10% annually
uint256 constant MAX_MINT_FEE = 0.05e18; // D18{1} 5%
uint256 constant MIN_MINT_FEE = 0.0003e18; // D18{1} 0.03%
uint256 constant MIN_AUCTION_LENGTH = 60; // {s} 1 min
uint256 constant MAX_AUCTION_LENGTH = 604800; // {s} 1 week
uint256 constant MAX_FEE_RECIPIENTS = 64;
uint256 constant MAX_TTL = 604800 * 4; // {s} 4 weeks
uint256 constant MAX_LIMIT = 1e27; // D18{BU/share}
uint256 constant MAX_WEIGHT = 1e54; // D27{tok/BU}
uint256 constant MAX_TOKEN_BUY_AMOUNT = 1e36; // {tok}
uint256 constant MAX_TOKEN_PRICE = 1e45; // D27{UoA/tok}
uint256 constant MAX_TOKEN_PRICE_RANGE = 1e2; // {1}
uint256 constant RESTRICTED_AUCTION_BUFFER = 120; // {s} 2 min
uint256 constant ONE_OVER_YEAR = 31709791983; // D18{1/s} 1e18 / 31536000
uint256 constant ONE_DAY = 24 hours; // {s} 1 day
uint256 constant D18 = 1e18; // D18
uint256 constant D27 = 1e27; // D27
bytes32 constant DEFAULT_ADMIN_ROLE = 0x00;
bytes32 constant AUCTION_APPROVER = keccak256("AUCTION_APPROVER"); // 0x2be23b023f3eee571adc019cdcf3f0bcf041151e6ff405a4bf0c4bfc6faea8c9 DEPRECATED
bytes32 constant REBALANCE_MANAGER = keccak256("REBALANCE_MANAGER"); // 0x4ff6ae4d6a29e79ca45c6441bdc89b93878ac6118485b33c8baa3749fc3cb130
bytes32 constant AUCTION_LAUNCHER = keccak256("AUCTION_LAUNCHER"); // 0x13ff1b2625181b311f257c723b5e6d366eb318b212d9dd694c48fcf227659df5
bytes32 constant BRAND_MANAGER = keccak256("BRAND_MANAGER"); // 0x2d8e650da9bd8c373ab2450d770f2ed39549bfc28d3630025cecc51511bcd374
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 constant ERC20_STORAGE_LOCATION = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
// This value should be updated on each release
string constant VERSION = "5.0.0";
/**
* @title Versioned
* @notice A mix-in to track semantic versioning uniformly across contracts.
*/
abstract contract Versioned {
function version() public pure virtual returns (string memory) {
return VERSION;
}
}// 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) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { ERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import { ERC20Votes } from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import { ERC4626 } from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Nonces } from "@openzeppelin/contracts/utils/Nonces.sol";
import { Time } from "@openzeppelin/contracts/utils/types/Time.sol";
import { UD60x18 } from "@prb/math/src/UD60x18.sol";
import { UnstakingManager } from "./UnstakingManager.sol";
uint256 constant MAX_UNSTAKING_DELAY = 4 weeks; // {s}
uint256 constant MAX_REWARD_HALF_LIFE = 2 weeks; // {s}
uint256 constant MIN_REWARD_HALF_LIFE = 1 days; // {s}
uint256 constant LN_2 = 0.693147180559945309e18; // D18{1} ln(2e18)
uint256 constant SCALAR = 1e18; // D18
/**
* @title StakingVault
* @author akshatmittal, julianmrodri, pmckelvy1, tbrent
* @notice StakingVault is a transferrable vault of an underlying token that uses the ERC4626 interface.
* It earns the holder a claimable stream of multi rewards and enables them to vote in (external) governance.
* Unstaking is gated by a delay, implemented by an UnstakingManager.
* @dev StakingVault also supports native asset() rewards alongside other reward tokens, but are handled independently.
*/
contract StakingVault is ERC4626, ERC20Permit, ERC20Votes, Ownable {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet private rewardTokens;
uint256 public rewardRatio; // D18{1}
UnstakingManager public immutable unstakingManager;
uint256 public unstakingDelay; // {s}
struct RewardInfo {
uint256 payoutLastPaid; // {s}
uint256 rewardIndex; // D18+decimals{reward/share}
//
uint256 balanceAccounted; // {reward}
uint256 balanceLastKnown; // {reward}
uint256 totalClaimed; // {reward}
}
struct UserRewardInfo {
uint256 lastRewardIndex; // D18+decimals{reward/share}
uint256 accruedRewards; // {reward}
}
mapping(address token => RewardInfo rewardInfo) public rewardTrackers;
mapping(address token => bool isDisallowed) public disallowedRewardTokens;
mapping(address token => mapping(address user => UserRewardInfo userReward)) public userRewardTrackers;
uint256 private totalDeposited; // {asset}
uint256 private nativeRewardsLastPaid; // {s}
error Vault__InvalidRewardToken(address rewardToken);
error Vault__DisallowedRewardToken(address rewardToken);
error Vault__RewardAlreadyRegistered();
error Vault__RewardNotRegistered();
error Vault__InvalidUnstakingDelay();
error Vault__InvalidRewardsHalfLife();
event UnstakingDelaySet(uint256 delay);
event RewardTokenAdded(address rewardToken);
event RewardTokenRemoved(address rewardToken);
event RewardsClaimed(address user, address rewardToken, uint256 amount);
event RewardRatioSet(uint256 rewardRatio, uint256 halfLife);
/// @param _name Name of the vault
/// @param _symbol Symbol of the vault
/// @param _underlying Underlying token deposited during staking
/// @param _initialOwner Initial owner of the vault
/// @param _rewardPeriod {s} Half life of the reward handout rate
/// @param _unstakingDelay {s} Delay after unstaking before user receives their deposit
constructor(
string memory _name,
string memory _symbol,
IERC20 _underlying,
address _initialOwner,
uint256 _rewardPeriod,
uint256 _unstakingDelay
) ERC4626(_underlying) ERC20(_name, _symbol) ERC20Permit(_name) Ownable(_initialOwner) {
_setRewardRatio(_rewardPeriod);
_setUnstakingDelay(_unstakingDelay);
unstakingManager = new UnstakingManager(_underlying);
nativeRewardsLastPaid = block.timestamp;
}
/**
* Deposit & Delegate
*/
function depositAndDelegate(uint256 assets) external returns (uint256 shares) {
shares = deposit(assets, msg.sender);
_delegate(msg.sender, msg.sender);
}
function totalAssets() public view override returns (uint256) {
// {qAsset} = {qAsset} + {qAsset}
return totalDeposited + _currentAccountedNativeRewards();
}
function _currentAccountedNativeRewards() internal view returns (uint256) {
uint256 elapsed = block.timestamp - nativeRewardsLastPaid;
uint256 rewardsBalance = IERC20(asset()).balanceOf(address(this)) - totalDeposited;
return _calculateHandout(rewardsBalance, elapsed);
}
function _deposit(
address caller,
address receiver,
uint256 assets,
uint256 shares
) internal override accrueRewards(caller, receiver) {
totalDeposited += assets;
super._deposit(caller, receiver, assets, shares);
}
/**
* Withdraw Logic
*/
function _withdraw(
address _caller,
address _receiver,
address _owner,
uint256 _assets,
uint256 _shares
) internal override accrueRewards(_owner, _receiver) {
totalDeposited -= _assets;
if (unstakingDelay == 0) {
super._withdraw(_caller, _receiver, _owner, _assets, _shares);
} else {
// Since we can't use the builtin `_withdraw`, we need to take care of the entire flow here.
if (_caller != _owner) {
_spendAllowance(_owner, _caller, _shares);
}
// Burn the shares first.
_burn(_owner, _shares);
SafeERC20.forceApprove(IERC20(asset()), address(unstakingManager), _assets);
unstakingManager.createLock(_receiver, _assets, block.timestamp + unstakingDelay);
emit Withdraw(_caller, _receiver, _owner, _assets, _shares);
}
}
/// @param _delay {s} New unstaking delay
function setUnstakingDelay(uint256 _delay) external onlyOwner {
_setUnstakingDelay(_delay);
}
/// @param _delay {s} New unstaking delay
function _setUnstakingDelay(uint256 _delay) internal {
require(_delay <= MAX_UNSTAKING_DELAY, Vault__InvalidUnstakingDelay());
unstakingDelay = _delay;
emit UnstakingDelaySet(_delay);
}
/**
* Reward Management Logic
*/
/// @param _rewardToken Reward token to add
function addRewardToken(address _rewardToken) external onlyOwner {
require(_rewardToken != address(this) && _rewardToken != asset(), Vault__InvalidRewardToken(_rewardToken));
require(!disallowedRewardTokens[_rewardToken], Vault__DisallowedRewardToken(_rewardToken));
require(rewardTokens.add(_rewardToken), Vault__RewardAlreadyRegistered());
RewardInfo storage rewardInfo = rewardTrackers[_rewardToken];
rewardInfo.payoutLastPaid = block.timestamp;
rewardInfo.balanceLastKnown = IERC20(_rewardToken).balanceOf(address(this));
emit RewardTokenAdded(_rewardToken);
}
/// @param _rewardToken Reward token to remove
function removeRewardToken(address _rewardToken) external onlyOwner {
disallowedRewardTokens[_rewardToken] = true;
require(rewardTokens.remove(_rewardToken), Vault__RewardNotRegistered());
emit RewardTokenRemoved(_rewardToken);
}
/// Allows to claim rewards
/// Supports claiming accrued rewards for disallowed/removed tokens
/// @param _rewardTokens Array of reward tokens to claim
/// @return claimableRewards Amount claimed for each rewardToken
function claimRewards(
address[] calldata _rewardTokens
) external accrueRewards(msg.sender, msg.sender) returns (uint256[] memory claimableRewards) {
claimableRewards = new uint256[](_rewardTokens.length);
for (uint256 i; i < _rewardTokens.length; i++) {
address _rewardToken = _rewardTokens[i];
RewardInfo storage rewardInfo = rewardTrackers[_rewardToken];
UserRewardInfo storage userRewardTracker = userRewardTrackers[_rewardToken][msg.sender];
claimableRewards[i] = userRewardTracker.accruedRewards;
if (claimableRewards[i] != 0) {
// {reward} += {reward}
rewardInfo.totalClaimed += claimableRewards[i];
userRewardTracker.accruedRewards = 0;
SafeERC20.safeTransfer(IERC20(_rewardToken), msg.sender, claimableRewards[i]);
emit RewardsClaimed(msg.sender, _rewardToken, claimableRewards[i]);
}
}
}
function getAllRewardTokens() external view returns (address[] memory) {
return rewardTokens.values();
}
/**
* Reward Accrual Logic
*/
/// @param rewardHalfLife {s}
function setRewardRatio(uint256 rewardHalfLife) external onlyOwner {
_setRewardRatio(rewardHalfLife);
}
/// @param _rewardHalfLife {s}
function _setRewardRatio(uint256 _rewardHalfLife) internal accrueRewards(msg.sender, msg.sender) {
require(
_rewardHalfLife <= MAX_REWARD_HALF_LIFE && _rewardHalfLife >= MIN_REWARD_HALF_LIFE,
Vault__InvalidRewardsHalfLife()
);
// D18{1/s} = D18{1} / {s}
rewardRatio = LN_2 / _rewardHalfLife;
emit RewardRatioSet(rewardRatio, _rewardHalfLife);
}
function poke() external accrueRewards(msg.sender, msg.sender) {}
modifier accrueRewards(address _caller, address _receiver) {
_accrueRewards(_caller, _receiver);
_;
}
function _accrueRewards(address _caller, address _receiver) internal {
address[] memory _rewardTokens = rewardTokens.values();
uint256 _rewardTokensLength = _rewardTokens.length;
for (uint256 i; i < _rewardTokensLength; i++) {
address rewardToken = _rewardTokens[i];
_accrueRewards(rewardToken);
_accrueUser(_receiver, rewardToken);
// If a deposit/withdraw operation gets called for another user we should
// accrue for both of them to avoid potential issues
// This is important for accruing for "from" and "to" in a transfer.
if (_receiver != _caller) {
_accrueUser(_caller, rewardToken);
}
}
/**
* Native asset() rewards are special cased
*/
totalDeposited += _currentAccountedNativeRewards();
nativeRewardsLastPaid = block.timestamp;
}
function _accrueRewards(address _rewardToken) internal {
RewardInfo storage rewardInfo = rewardTrackers[_rewardToken];
uint256 balanceLastKnown = rewardInfo.balanceLastKnown;
rewardInfo.balanceLastKnown = IERC20(_rewardToken).balanceOf(address(this)) + rewardInfo.totalClaimed;
uint256 elapsed = block.timestamp - rewardInfo.payoutLastPaid;
uint256 unaccountedBalance = balanceLastKnown - rewardInfo.balanceAccounted;
uint256 tokensToHandout = _calculateHandout(unaccountedBalance, elapsed);
if (tokensToHandout != 0) {
// D18+decimals{reward/share} = D18 * {reward} * decimals / {share}
uint256 deltaIndex = (SCALAR * tokensToHandout * uint256(10 ** decimals())) / totalSupply();
// D18+decimals{reward/share} += D18+decimals{reward/share}
rewardInfo.rewardIndex += deltaIndex;
rewardInfo.balanceAccounted += tokensToHandout;
}
rewardInfo.payoutLastPaid = block.timestamp;
}
function _accrueUser(address _user, address _rewardToken) internal {
if (_user == address(0)) {
return;
}
RewardInfo memory rewardInfo = rewardTrackers[_rewardToken];
UserRewardInfo storage userRewardTracker = userRewardTrackers[_rewardToken][_user];
// D18+decimals{reward/share}
uint256 deltaIndex = rewardInfo.rewardIndex - userRewardTracker.lastRewardIndex;
if (deltaIndex != 0) {
// Accumulate rewards by multiplying user tokens by index and adding on unclaimed
// {reward} = {share} * D18+decimals{reward/share} / decimals / D18
uint256 supplierDelta = (balanceOf(_user) * deltaIndex) / uint256(10 ** decimals()) / SCALAR;
// {reward} += {reward}
userRewardTracker.accruedRewards += supplierDelta;
userRewardTracker.lastRewardIndex = rewardInfo.rewardIndex;
}
}
/**
* @dev Uses global `rewardRatio`
*/
function _calculateHandout(
uint256 balanceAvailable,
uint256 elapsed
) internal view returns (uint256 tokensToHandout) {
// The checks are in order of likelihood to save gas
if (balanceAvailable == 0 || elapsed == 0 || totalSupply() == 0) {
return 0;
}
uint256 handoutPercentage = 1e18 - UD60x18.wrap(1e18 - rewardRatio).powu(elapsed).unwrap() - 1; // rounds down
// {reward|asset} = {reward|asset} * D18{1} / D18
tokensToHandout = (balanceAvailable * handoutPercentage) / 1e18;
}
/**
* Overrides
*/
function _update(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Votes) accrueRewards(from, to) {
super._update(from, to, value);
}
function nonces(address _owner) public view override(ERC20Permit, Nonces) returns (uint256) {
return super.nonces(_owner);
}
function decimals() public view virtual override(ERC20, ERC4626) returns (uint8) {
return super.decimals();
}
/**
* ERC5805 Clock
*/
function clock() public view override returns (uint48) {
return Time.timestamp();
}
function CLOCK_MODE() public pure override returns (string memory) {
return "mode=timestamp";
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/AccessControlEnumerable.sol)
pragma solidity ^0.8.20;
import {IAccessControlEnumerable} from "@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerable, AccessControlUpgradeable {
using EnumerableSet for EnumerableSet.AddressSet;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControlEnumerable
struct AccessControlEnumerableStorage {
mapping(bytes32 role => EnumerableSet.AddressSet) _roleMembers;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlEnumerable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlEnumerableStorageLocation = 0xc1f6fe24621ce81ec5827caf0253cadb74709b061630e6b55e82371705932000;
function _getAccessControlEnumerableStorage() private pure returns (AccessControlEnumerableStorage storage $) {
assembly {
$.slot := AccessControlEnumerableStorageLocation
}
}
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].length();
}
/**
* @dev Return all accounts that have `role`
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function getRoleMembers(bytes32 role) public view virtual returns (address[] memory) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].values();
}
/**
* @dev Overload {AccessControl-_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
bool granted = super._grantRole(role, account);
if (granted) {
$._roleMembers[role].add(account);
}
return granted;
}
/**
* @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
bool revoked = super._revokeRole(role, account);
if (revoked) {
$._roleMembers[role].remove(account);
}
return revoked;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* 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 {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```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 {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}// 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
pragma solidity ^0.8.19;
import { IBaseTrustedFiller } from "./IBaseTrustedFiller.sol";
interface ITrustedFillerRegistry {
error TrustedFillerRegistry__InvalidCaller();
error TrustedFillerRegistry__InvalidRoleRegistry();
error TrustedFillerRegistry__InvalidFiller();
event TrustedFillerCreated(address creator, IBaseTrustedFiller filler);
event TrustedFillerAdded(IBaseTrustedFiller filler);
event TrustedFillerDeprecated(IBaseTrustedFiller filler);
function addTrustedFiller(IBaseTrustedFiller _filler) external;
function deprecateTrustedFiller(IBaseTrustedFiller _filler) external;
function createTrustedFiller(
address senderSource,
address trustedFiller,
bytes32 deploymentSalt
) external returns (IBaseTrustedFiller trustedFillerInstance);
function isAllowed(address _filler) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { IBaseTrustedFiller } from "@reserve-protocol/trusted-fillers/contracts/interfaces/IBaseTrustedFiller.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IBidderCallee } from "@interfaces/IBidderCallee.sol";
import { IFolio } from "@interfaces/IFolio.sol";
import { AUCTION_WARMUP, D18, D27, MAX_TOKEN_BUY_AMOUNT, MAX_LIMIT, MAX_WEIGHT, MAX_TOKEN_PRICE, MAX_TOKEN_PRICE_RANGE, MAX_TTL } from "@utils/Constants.sol";
import { MathLib } from "@utils/MathLib.sol";
/**
* @title RebalancingLib
* @notice Library for rebalancing/auction operations
* @author akshatmittal, julianmrodri, pmckelvy1, tbrent
*
* startRebalance() -> openAuction() -> getBid() -> bid()
*/
library RebalancingLib {
function startRebalance(
address[] calldata oldTokens,
IFolio.RebalanceControl storage rebalanceControl,
IFolio.Rebalance storage rebalance,
IFolio.TokenRebalanceParams[] calldata tokens,
IFolio.RebalanceLimits calldata limits,
uint256 auctionLauncherWindow,
uint256 ttl,
bool bidsEnabled
) external {
// remove old tokens from rebalance while keeping them in the basket
for (uint256 i; i < oldTokens.length; i++) {
delete rebalance.details[oldTokens[i]];
}
// ====
require(ttl != 0 && ttl >= auctionLauncherWindow && ttl <= MAX_TTL, IFolio.Folio__InvalidTTL());
// enforce limits are internally consistent
require(
limits.low != 0 && limits.low <= limits.spot && limits.spot <= limits.high && limits.high <= MAX_LIMIT,
IFolio.Folio__InvalidLimits()
);
uint256 len = tokens.length;
require(len > 1, IFolio.Folio__EmptyRebalance());
// set new rebalance details and prices
for (uint256 i; i < len; i++) {
IFolio.TokenRebalanceParams calldata params = tokens[i];
require(params.inRebalance, IFolio.Folo__NotInRebalance());
// enforce valid token
require(params.token != address(0) && params.token != address(this), IFolio.Folio__InvalidAsset());
// enforce no duplicates
require(!rebalance.details[params.token].inRebalance, IFolio.Folio__DuplicateAsset());
if (!rebalanceControl.weightControl) {
// weights must be fixed
require(
params.weight.low == params.weight.spot &&
params.weight.spot == params.weight.high &&
params.weight.high <= MAX_WEIGHT,
IFolio.Folio__InvalidWeights()
);
} else {
// weights can be revised within bounds
require(
params.weight.low <= params.weight.spot &&
params.weight.spot <= params.weight.high &&
params.weight.high <= MAX_WEIGHT,
IFolio.Folio__InvalidWeights()
);
// ensure removeFromBasket() cannot be griefed
require(params.weight.spot != 0 || params.weight.high == 0, IFolio.Folio__InvalidWeights());
}
// enforce prices are internally consistent
require(
params.price.low != 0 &&
params.price.low < params.price.high &&
params.price.high <= MAX_TOKEN_PRICE &&
params.price.high <= MAX_TOKEN_PRICE_RANGE * params.price.low,
IFolio.Folio__InvalidPrices()
);
rebalance.details[params.token] = IFolio.RebalanceDetails({
inRebalance: true,
weights: params.weight,
initialPrices: params.price,
maxAuctionSize: params.maxAuctionSize
});
}
rebalance.nonce++;
rebalance.limits = limits;
rebalance.startedAt = block.timestamp;
rebalance.restrictedUntil = block.timestamp + auctionLauncherWindow;
rebalance.availableUntil = block.timestamp + ttl;
rebalance.priceControl = rebalanceControl.priceControl;
rebalance.bidsEnabled = bidsEnabled;
emit IFolio.RebalanceStarted(
rebalance.nonce,
rebalance.priceControl,
tokens,
limits,
block.timestamp,
block.timestamp + auctionLauncherWindow,
block.timestamp + ttl,
bidsEnabled
);
}
/// Open a new auction
function openAuction(
IFolio.Rebalance storage rebalance,
mapping(uint256 auctionId => IFolio.Auction) storage auctions,
uint256 auctionId,
address[] memory tokens,
IFolio.WeightRange[] memory weights,
IFolio.PriceRange[] calldata prices,
IFolio.RebalanceLimits calldata limits,
uint256 auctionLength
) external {
uint256 len = tokens.length;
require(len != 0 && len == weights.length && len == prices.length, IFolio.Folio__InvalidArrayLengths());
// narrow rebalance limits
{
IFolio.RebalanceLimits storage rebalanceLimits = rebalance.limits;
// enforce new limits are valid
require(
rebalanceLimits.low <= limits.low &&
limits.low <= limits.spot &&
limits.spot <= limits.high &&
limits.high <= rebalanceLimits.high,
IFolio.Folio__InvalidLimits()
);
rebalanceLimits.low = limits.low;
rebalanceLimits.spot = limits.spot;
rebalanceLimits.high = limits.high;
}
IFolio.Auction storage auction = auctions[auctionId];
// use first tokens as anchor for atomic swap check
bool allAtomicSwaps = prices[0].low == prices[0].high;
// all tokens must have constant prices or none can
require(
!allAtomicSwaps || rebalance.priceControl == IFolio.PriceControl.ATOMIC_SWAP,
IFolio.Folio__InvalidPrices()
);
// update basket weights + auction prices
for (uint256 i = 0; i < len; i++) {
address token = tokens[i];
// enforce unique
require(auction.prices[token].high == 0, IFolio.Folio__DuplicateAsset());
IFolio.RebalanceDetails storage rebalanceDetails = rebalance.details[token];
// enforce valid token
require(
token != address(0) && token != address(this) && rebalanceDetails.inRebalance,
IFolio.Folio__InvalidAsset()
);
// update weights
{
require(
rebalanceDetails.weights.low <= weights[i].low &&
weights[i].low <= weights[i].spot &&
weights[i].spot <= weights[i].high &&
weights[i].high <= rebalanceDetails.weights.high,
IFolio.Folio__InvalidWeights()
);
rebalanceDetails.weights = weights[i];
}
// save auction prices
{
if (rebalance.priceControl == IFolio.PriceControl.NONE) {
// prices must be exactly the initial prices
require(
prices[i].low == rebalanceDetails.initialPrices.low &&
prices[i].high == rebalanceDetails.initialPrices.high,
IFolio.Folio__InvalidPrices()
);
} else {
// prices can be revised within the bounds of the initial prices
require(
prices[i].low >= rebalanceDetails.initialPrices.low &&
prices[i].high <= rebalanceDetails.initialPrices.high &&
prices[i].high >= prices[i].low,
IFolio.Folio__InvalidPrices()
);
// everything must be an atomic swap or nothing can be
require(allAtomicSwaps == (prices[i].low == prices[i].high), IFolio.Folio__MixedAtomicSwaps());
}
auction.prices[token] = prices[i];
}
}
// save auction
auction.rebalanceNonce = rebalance.nonce;
if (allAtomicSwaps) {
// atomic swaps start and end at same timestamp
auction.startTime = block.timestamp;
auction.endTime = block.timestamp;
} else {
// auctions begin after a 30s warmup period
auction.startTime = block.timestamp + AUCTION_WARMUP;
auction.endTime = block.timestamp + AUCTION_WARMUP + auctionLength;
}
emit IFolio.AuctionOpened(
rebalance.nonce,
auctionId,
tokens,
weights,
prices,
limits,
auction.startTime,
auction.endTime
);
}
/// @dev stack-too-deep
/// @param totalSupply {share} Current total supply of the Folio
/// @param sellBal {sellTok} Folio's available balance of sell token, including any active fills
/// @param buyBal {buyTok} Folio's available balance of buy token, including any active fills
/// @param minSellAmount {sellTok} The minimum sell amount the bidder should receive
/// @param maxSellAmount {sellTok} The maximum sell amount the bidder should receive
/// @param maxBuyAmount {buyTok} The maximum buy amount the bidder is willing to offer
struct GetBidParams {
uint256 totalSupply;
uint256 sellBal;
uint256 buyBal;
uint256 minSellAmount;
uint256 maxSellAmount;
uint256 maxBuyAmount;
}
/// Get bid parameters for an ongoing auction at the current timestamp
/// @return sellAmount {sellTok} The actual sell amount in the bid
/// @return bidAmount {buyTok} The corresponding buy amount
/// @return price D27{buyTok/sellTok} The price at the given timestamp as an 27-decimal fixed point
function getBid(
IFolio.Rebalance storage rebalance,
IFolio.Auction storage auction,
IERC20 sellToken,
IERC20 buyToken,
GetBidParams memory params
) external view returns (uint256 sellAmount, uint256 bidAmount, uint256 price) {
assert(params.minSellAmount <= params.maxSellAmount);
// checks auction is ongoing and part of rebalance
// D27{buyTok/sellTok}
price = _price(rebalance, auction, sellToken, buyToken);
uint256 buyAvailable;
{
IFolio.RebalanceDetails memory buyDetails = rebalance.details[address(buyToken)];
// buy up to the low BU limit and low weight
// D27{buyTok/share} = D18{BU/share} * D27{buyTok/BU} / D18
uint256 buyLimit = Math.mulDiv(rebalance.limits.low, buyDetails.weights.low, D18, Math.Rounding.Floor);
// {buyTok} = D27{buyTok/share} * {share} / D27
uint256 buyLimitBal = Math.mulDiv(buyLimit, params.totalSupply, D27, Math.Rounding.Floor);
buyAvailable = params.buyBal < buyLimitBal ? buyLimitBal - params.buyBal : 0;
// max auction size
// {buyTok}
uint256 buyRemaining = buyDetails.maxAuctionSize > auction.traded[address(buyToken)]
? buyDetails.maxAuctionSize - auction.traded[address(buyToken)]
: 0;
buyAvailable = Math.min(buyAvailable, buyRemaining);
// maximum valid token purchase is 1e36; do not try to buy more than this
buyAvailable = Math.min(buyAvailable, MAX_TOKEN_BUY_AMOUNT);
}
uint256 sellAvailable;
{
IFolio.RebalanceDetails memory sellDetails = rebalance.details[address(sellToken)];
// sell down to the high BU limit and high weight
// D27{sellTok/share} = D18{BU/share} * D27{sellTok/BU} / D18
uint256 sellLimit = Math.mulDiv(rebalance.limits.high, sellDetails.weights.high, D18, Math.Rounding.Ceil);
// {sellTok} = D27{sellTok/share} * {share} / D27
uint256 sellLimitBal = Math.mulDiv(sellLimit, params.totalSupply, D27, Math.Rounding.Ceil);
sellAvailable = params.sellBal > sellLimitBal ? params.sellBal - sellLimitBal : 0;
// {sellTok} = {buyTok} * D27 / D27{buyTok/sellTok}
uint256 sellAvailableFromBuy = Math.mulDiv(buyAvailable, D27, price, Math.Rounding.Floor);
sellAvailable = Math.min(sellAvailable, sellAvailableFromBuy);
// max auction size
// {sellTok}
uint256 sellRemaining = sellDetails.maxAuctionSize > auction.traded[address(sellToken)]
? sellDetails.maxAuctionSize - auction.traded[address(sellToken)]
: 0;
sellAvailable = Math.min(sellAvailable, sellRemaining);
}
// ensure auction is large enough to cover bid
require(sellAvailable >= params.minSellAmount, IFolio.Folio__InsufficientSellAvailable());
// {sellTok}
sellAmount = Math.min(sellAvailable, params.maxSellAmount);
// {buyTok} = {sellTok} * D27{buyTok/sellTok} / D27
bidAmount = Math.mulDiv(sellAmount, price, D27, Math.Rounding.Ceil);
require(bidAmount <= params.maxBuyAmount, IFolio.Folio__SlippageExceeded());
}
/// Bid in an ongoing auction
/// If withCallback is true, caller must adhere to IBidderCallee interface and receives a callback
/// If withCallback is false, caller must have provided an allowance in advance
/// @param sellAmount {sellTok} Sell amount as returned by getBid
/// @param bidAmount {buyTok} Bid amount as returned by getBid
/// @param withCallback If true, caller must adhere to IBidderCallee interface and transfers tokens via callback
/// @param data Arbitrary data to pass to the callback
/// @return shouldRemoveFromBasket If true, the auction's sell token should be removed from the basket after
function bid(
IFolio.Auction storage auction,
uint256 auctionId,
IERC20 sellToken,
IERC20 buyToken,
uint256 sellAmount,
uint256 bidAmount,
bool withCallback,
bytes calldata data
) external returns (bool shouldRemoveFromBasket) {
require(bidAmount != 0, IFolio.Folio__InsufficientBuyAvailable());
// {sellTok}
uint256 sellBalBefore = sellToken.balanceOf(address(this));
// pay bidder
SafeERC20.safeTransfer(sellToken, msg.sender, sellAmount);
// {buyTok}
uint256 buyBalBefore = buyToken.balanceOf(address(this));
// collect payment from bidder
if (withCallback) {
IBidderCallee(msg.sender).bidCallback(address(buyToken), bidAmount, data);
} else {
SafeERC20.safeTransferFrom(buyToken, msg.sender, address(this), bidAmount);
}
uint256 bought;
{
uint256 buyBalAfter = buyToken.balanceOf(address(this));
bought = buyBalAfter > buyBalBefore ? buyBalAfter - buyBalBefore : 0;
require(bought >= bidAmount, IFolio.Folio__InsufficientBid());
}
uint256 sellBalAfter = sellToken.balanceOf(address(this));
uint256 sold = sellBalBefore > sellBalAfter ? sellBalBefore - sellBalAfter : 0;
// track traded amts
auction.traded[address(sellToken)] += sold;
auction.traded[address(buyToken)] += bought;
emit IFolio.AuctionBid(auctionId, address(sellToken), address(buyToken), sold, bought);
// shouldRemoveFromBasket
return sellBalAfter == 0;
}
/// Close a trusted fill
/// @param auction The current ongoing auction
/// @param activeTrustedFill The active trusted fill to close
function closeTrustedFill(IFolio.Auction storage auction, IBaseTrustedFiller activeTrustedFill) external {
IERC20 sellToken = activeTrustedFill.sellToken();
IERC20 buyToken = activeTrustedFill.buyToken();
uint256 sellBalBefore = sellToken.balanceOf(address(this)); // {sellTok}
uint256 buyBalBefore = buyToken.balanceOf(address(this)); // {buyTok}
activeTrustedFill.closeFiller();
// {sellTok}
uint256 sellBalAfter = sellToken.balanceOf(address(this));
uint256 sellReturned = sellBalAfter > sellBalBefore ? sellBalAfter - sellBalBefore : 0;
// {sellTok}
uint256 sellAmount = activeTrustedFill.sellAmount();
uint256 sold = sellAmount > sellReturned ? sellAmount - sellReturned : 0;
// {buyTok}
uint256 buyBalAfter = buyToken.balanceOf(address(this));
uint256 bought = buyBalAfter > buyBalBefore ? buyBalAfter - buyBalBefore : 0;
// track traded amts
auction.traded[address(sellToken)] += sold;
auction.traded[address(buyToken)] += bought;
// no event, cannot rely on executing in same block as fill occurred
}
// ==== Internal ====
/// Get the price of a token pair within an auction at the current timestamp
/// If startTime == endTime, startPrice is used.
/// @return p D27{buyTok/sellTok}
function _price(
IFolio.Rebalance storage rebalance,
IFolio.Auction storage auction,
IERC20 sellToken,
IERC20 buyToken
) internal view returns (uint256 p) {
IFolio.PriceRange memory sellPrices = auction.prices[address(sellToken)];
IFolio.PriceRange memory buyPrices = auction.prices[address(buyToken)];
// ensure auction is ongoing and token pair is in it
require(
auction.rebalanceNonce == rebalance.nonce &&
sellToken != buyToken &&
rebalance.details[address(sellToken)].inRebalance &&
rebalance.details[address(buyToken)].inRebalance &&
sellPrices.low != 0 && // in auction check
buyPrices.low != 0 && // in auction check
block.timestamp >= auction.startTime &&
block.timestamp <= auction.endTime,
IFolio.Folio__AuctionNotOngoing()
);
// D27{buyTok/sellTok} = D27{UoA/sellTok} * D27 / D27{UoA/buyTok}
uint256 startPrice = Math.mulDiv(sellPrices.high, D27, buyPrices.low, Math.Rounding.Ceil);
if (block.timestamp == auction.startTime) {
return startPrice;
}
// D27{buyTok/sellTok} = D27{UoA/sellTok} * D27 / D27{UoA/buyTok}
uint256 endPrice = Math.mulDiv(sellPrices.low, D27, buyPrices.high, Math.Rounding.Ceil);
if (block.timestamp == auction.endTime) {
return endPrice;
}
// {s}
uint256 elapsed = block.timestamp - auction.startTime;
uint256 auctionLength = auction.endTime - auction.startTime;
// D18{1}
// k = ln(P_0 / P_t) / t
uint256 k = MathLib.ln(Math.mulDiv(startPrice, D18, endPrice)) / auctionLength;
// P_t = P_0 * e ^ -kt
// D27{buyTok/sellTok} = D27{buyTok/sellTok} * D18{1} / D18
p = Math.mulDiv(startPrice, MathLib.exp(-1 * int256(k * elapsed)), D18, Math.Rounding.Ceil);
if (p < endPrice) {
p = endPrice;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { UD60x18, pow as UD_pow, powu as UD_powu, ln as UD_ln } from "@prb/math/src/UD60x18.sol";
import { SD59x18, intoUint256, exp as SD_exp } from "@prb/math/src/SD59x18.sol";
library MathLib {
/// @param x 18 decimal fixed point
/// @param y 18 decimal fixed point
/// @return z 18 decimal fixed point
function pow(uint256 x, uint256 y) external pure returns (uint256 z) {
return UD_pow(UD60x18.wrap(x), UD60x18.wrap(y)).unwrap();
}
/// @param x 18 decimal fixed point
/// @param y whole number exponent
/// @return z 18 decimal fixed point
function powu(uint256 x, uint256 y) external pure returns (uint256 z) {
return UD_powu(UD60x18.wrap(x), y).unwrap();
}
// ==== Internal ====
/// @param x 18 decimal fixed point
/// @return z 18 decimal fixed point
function ln(uint256 x) internal pure returns (uint256 z) {
return UD_ln(UD60x18.wrap(x)).unwrap();
}
/// @param x 18 decimal fixed point
/// @return z 18 decimal fixed point
function exp(int256 x) internal pure returns (uint256 z) {
return intoUint256(SD_exp(SD59x18.wrap(x)));
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IFolioDAOFeeRegistry {
error FolioDAOFeeRegistry__FeeRecipientAlreadySet();
error FolioDAOFeeRegistry__InvalidFeeRecipient();
error FolioDAOFeeRegistry__InvalidFeeNumerator();
error FolioDAOFeeRegistry__InvalidRoleRegistry();
error FolioDAOFeeRegistry__InvalidCaller();
error FolioDAOFeeRegistry__InvalidFeeFloor();
event FeeRecipientSet(address indexed feeRecipient);
event DefaultFeeNumeratorSet(uint256 defaultFeeNumerator);
event TokenFeeFloorSet(address indexed rToken, uint256 feeFloor, bool isActive);
event TokenFeeNumeratorSet(address indexed rToken, uint256 feeNumerator, bool isActive);
event DefaultFeeFloorSet(uint256 feeFloor);
function getFeeDetails(
address rToken
) external view returns (address recipient, uint256 feeNumerator, uint256 feeDenominator, uint256 feeFloor);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IFolio {
// === Events ===
event AuctionOpened(
uint256 indexed rebalanceNonce,
uint256 indexed auctionId,
address[] tokens,
WeightRange[] weights,
PriceRange[] prices,
RebalanceLimits limits,
uint256 startTime,
uint256 endTime
);
event AuctionBid(
uint256 indexed auctionId,
address indexed sellToken,
address indexed buyToken,
uint256 sellAmount,
uint256 buyAmount
);
event AuctionClosed(uint256 indexed auctionId);
event AuctionTrustedFillCreated(uint256 indexed auctionId, address filler);
event FolioFeePaid(address indexed recipient, uint256 amount);
event ProtocolFeePaid(address indexed recipient, uint256 amount);
event BasketTokenAdded(address indexed token);
event BasketTokenRemoved(address indexed token);
event TVLFeeSet(uint256 newFee, uint256 feeAnnually);
event MintFeeSet(uint256 newFee);
event FeeRecipientsSet(FeeRecipient[] recipients);
event AuctionLengthSet(uint256 newAuctionLength);
event MandateSet(string newMandate);
event TrustedFillerRegistrySet(address trustedFillerRegistry, bool isEnabled);
event FolioDeprecated();
event RebalanceControlSet(RebalanceControl newControl);
event RebalanceStarted(
uint256 indexed nonce,
PriceControl priceControl,
TokenRebalanceParams[] tokens,
RebalanceLimits limits,
uint256 startedAt,
uint256 restrictedUntil,
uint256 availableUntil,
bool bidsEnabled
);
event RebalanceEnded(uint256 nonce);
event BidsEnabledSet(bool bidsEnabled);
event NameSet(string newName);
// === Errors ===
error Folio__FolioDeprecated();
error Folio__Unauthorized();
error Folio__EmptyAssets();
error Folio__BasketModificationFailed();
error Folio__BalanceNotRemovable();
error Folio__FeeRecipientInvalidAddress();
error Folio__FeeRecipientInvalidFeeShare();
error Folio__BadFeeTotal();
error Folio__TVLFeeTooHigh();
error Folio__TVLFeeTooLow();
error Folio__MintFeeTooHigh();
error Folio__ZeroInitialShares();
error Folio__InvalidAsset();
error Folio__DuplicateAsset();
error Folio__InvalidAssetAmount(address asset);
error Folio__InvalidAuctionLength();
error Folio__InvalidLimits();
error Folio__InvalidWeights();
error Folio__AuctionCannotBeOpenedWithoutRestriction();
error Folio__AuctionNotOngoing();
error Folio__InvalidPrices();
error Folio__SlippageExceeded();
error Folio__InsufficientSellAvailable();
error Folio__InsufficientBuyAvailable();
error Folio__InsufficientBid();
error Folio__InsufficientSharesOut();
error Folio__TooManyFeeRecipients();
error Folio__InvalidArrayLengths();
error Folio__InvalidTransferToSelf();
error Folio__InvalidRegistry();
error Folio__TrustedFillerRegistryNotEnabled();
error Folio__TrustedFillerRegistryAlreadySet();
error Folio__InvalidTTL();
error Folio__NotRebalancing();
error Folio__MixedAtomicSwaps();
error Folio__PermissionlessBidsDisabled();
error Folio__EmptyRebalance();
error Folo__NotInRebalance();
// === Structures ===
/// Price control AUCTION_LAUNCHER has on rebalancing
enum PriceControl {
NONE, // cannot change prices
PARTIAL, // can set auction prices within bounds of initial prices
ATOMIC_SWAP // PARTIAL + ability to set startPrice equal to endPrice
}
struct FolioBasicDetails {
string name;
string symbol;
address[] assets;
uint256[] amounts; // {tok}
uint256 initialShares; // {share}
}
struct FolioAdditionalDetails {
uint256 auctionLength; // {s}
FeeRecipient[] feeRecipients;
uint256 tvlFee; // D18{1/s}
uint256 mintFee; // D18{1}
string mandate;
}
struct FolioRegistryIndex {
address daoFeeRegistry;
address trustedFillerRegistry;
}
struct FolioFlags {
bool trustedFillerEnabled;
RebalanceControl rebalanceControl;
bool bidsEnabled;
}
struct FeeRecipient {
address recipient;
uint96 portion; // D18{1}
}
/// AUCTION_LAUNCHER control over rebalancing
struct RebalanceControl {
bool weightControl; // if AUCTION_LAUNCHER can move weights
PriceControl priceControl; // if/how AUCTION_LAUNCHER can narrow prices
}
/// Basket limits for rebalancing
struct RebalanceLimits {
uint256 low; // D18{BU/share} (0, 1e27] to buy assets up to
uint256 spot; // D18{BU/share} (0, 1e27] point estimate to be used in the event of unrestricted caller
uint256 high; // D18{BU/share} (0, 1e27] to sell assets down to
}
/// Range of basket weights for BU definition
struct WeightRange {
uint256 low; // D27{tok/BU} [0, 1e54] to buy assets up to
uint256 spot; // D27{tok/BU} [0, 1e54] point estimate to be used in the event of unrestricted caller
uint256 high; // D27{tok/BU} [0, 1e54] to sell assets down to
}
/// Individual token price ranges
/// @dev Unit of Account (UoA) can be anything as long as it's consistent; nanoUSD is most common
struct PriceRange {
uint256 low; // D27{UoA/tok} (0, 1e45]
uint256 high; // D27{UoA/tok} (0, 1e45]
}
/// Rebalance details for a token (storage)
struct RebalanceDetails {
bool inRebalance;
WeightRange weights; // D27{tok/BU} [0, 1e54]
PriceRange initialPrices; // D27{UoA/tok} (0, 1e45]
uint256 maxAuctionSize; // {tok}
}
/// Singleton rebalance state
struct Rebalance {
uint256 nonce;
mapping(address token => RebalanceDetails) details;
RebalanceLimits limits; // D18{BU/share} (0, 1e27]
uint256 startedAt; // {s} timestamp rebalancing started, inclusive
uint256 restrictedUntil; // {s} timestamp rebalancing becomes unrestricted, exclusive
uint256 availableUntil; // {s} timestamp rebalancing ends overall, exclusive
PriceControl priceControl; // AUCTION_LAUNCHER control over auction pricing
bool bidsEnabled; // If true, permissionless bids are enabled
}
/// 1 running auction at a time; N per rebalance overall (storage)
/// Auction states:
/// - UNINITIALIZED: startTime == 0 && endTime == 0
/// - PENDING: block.timestamp < startTime
/// - OPEN: block.timestamp >= startTime && block.timestamp <= endTime
/// - CLOSED: block.timestamp > endTime
struct Auction {
uint256 rebalanceNonce;
mapping(address token => PriceRange) prices; // D27{UoA/tok} (0, 1e45]
uint256 startTime; // {s} inclusive
uint256 endTime; // {s} inclusive
mapping(address token => uint256) traded; // {tok}
}
/// Used to mark old storage slots now deprecated
struct DeprecatedStruct {
bytes32 EMPTY;
}
/// Token rebalance parameters (memory/calldata)
struct TokenRebalanceParams {
address token;
WeightRange weight; // D27{tok/BU} [0, 1e54]
PriceRange price; // D27{UoA/tok} (0, 1e45]
uint256 maxAuctionSize; // {tok}
bool inRebalance;
}
function distributeFees() external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
pragma solidity ^0.8.20;
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
import {ERC1967Proxy} from "../ERC1967/ERC1967Proxy.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {ProxyAdmin} from "./ProxyAdmin.sol";
/**
* @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
* does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch
* mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
* include them in the ABI so this interface must be used to interact with it.
*/
interface ITransparentUpgradeableProxy is IERC1967 {
/// @dev See {UUPSUpgradeable-upgradeToAndCall}
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable;
}
/**
* @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.
* 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to
* the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating
* the proxy admin cannot fallback to the target implementation.
*
* These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a
* dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to
* call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and
* allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative
* interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.
*
* NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
* inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch
* mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
* fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
* implementation.
*
* NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a
* meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.
*
* IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an
* immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be
* overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an
* undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot
* is generally fine if the implementation is trusted.
*
* WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the
* compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new
* function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This
* could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
// An immutable address for the admin to avoid unnecessary SLOADs before each call
// at the expense of removing the ability to change the admin once it's set.
// This is acceptable if the admin is always a ProxyAdmin instance or similar contract
// with its own ability to transfer the permissions to another account.
address private immutable _admin;
/**
* @dev The proxy caller is the current admin, and can't fallback to the proxy target.
*/
error ProxyDeniedAdminAccess();
/**
* @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,
* backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in
* {ERC1967Proxy-constructor}.
*/
constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
_admin = address(new ProxyAdmin(initialOwner));
// Set the storage value and emit an event for ERC-1967 compatibility
ERC1967Utils.changeAdmin(_proxyAdmin());
}
/**
* @dev Returns the admin of this proxy.
*/
function _proxyAdmin() internal view virtual returns (address) {
return _admin;
}
/**
* @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.
*/
function _fallback() internal virtual override {
if (msg.sender == _proxyAdmin()) {
if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
revert ProxyDeniedAdminAccess();
} else {
_dispatchUpgradeToAndCall();
}
} else {
super._fallback();
}
}
/**
* @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
function _dispatchUpgradeToAndCall() private {
(address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
ERC1967Utils.upgradeToAndCall(newImplementation, data);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.20;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { IFolioDeployer } from "@interfaces/IFolioDeployer.sol";
interface IFolioVersionRegistry {
error VersionRegistry__ZeroAddress();
error VersionRegistry__InvalidRegistration();
error VersionRegistry__AlreadyDeprecated();
error VersionRegistry__InvalidCaller();
error VersionRegistry__Unconfigured();
event VersionRegistered(bytes32 versionHash, IFolioDeployer folioDeployer);
event VersionDeprecated(bytes32 versionHash);
function getImplementationForVersion(bytes32 versionHash) external view returns (address folio);
function isDeprecated(bytes32 versionHash) external view returns (bool);
function deployments(bytes32 versionHash) external view returns (IFolioDeployer);
}// 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
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";
/**
* @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC-20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
return super.nonces(owner);
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/ERC20Votes.sol)
pragma solidity ^0.8.20;
import {ERC20} from "../ERC20.sol";
import {Votes} from "../../../governance/utils/Votes.sol";
import {Checkpoints} from "../../../utils/structs/Checkpoints.sol";
/**
* @dev Extension of ERC-20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^208^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: This contract does not provide interface compatibility with Compound's COMP token.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {Votes-delegate} function directly, or by providing a signature to be used with {Votes-delegateBySig}. Voting
* power can be queried through the public accessors {Votes-getVotes} and {Votes-getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
*/
abstract contract ERC20Votes is ERC20, Votes {
/**
* @dev Total supply cap has been exceeded, introducing a risk of votes overflowing.
*/
error ERC20ExceededSafeSupply(uint256 increasedSupply, uint256 cap);
/**
* @dev Maximum token supply. Defaults to `type(uint208).max` (2^208^ - 1).
*
* This maximum is enforced in {_update}. It limits the total supply of the token, which is otherwise a uint256,
* so that checkpoints can be stored in the Trace208 structure used by {Votes}. Increasing this value will not
* remove the underlying limitation, and will cause {_update} to fail because of a math overflow in
* {Votes-_transferVotingUnits}. An override could be used to further restrict the total supply (to a lower value) if
* additional logic requires it. When resolving override conflicts on this function, the minimum should be
* returned.
*/
function _maxSupply() internal view virtual returns (uint256) {
return type(uint208).max;
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {IVotes-DelegateVotesChanged} event.
*/
function _update(address from, address to, uint256 value) internal virtual override {
super._update(from, to, value);
if (from == address(0)) {
uint256 supply = totalSupply();
uint256 cap = _maxSupply();
if (supply > cap) {
revert ERC20ExceededSafeSupply(supply, cap);
}
}
_transferVotingUnits(from, to, value);
}
/**
* @dev Returns the voting units of an `account`.
*
* WARNING: Overriding this function may compromise the internal vote accounting.
* `ERC20Votes` assumes tokens map to voting units 1:1 and this is not easy to change.
*/
function _getVotingUnits(address account) internal view virtual override returns (uint256) {
return balanceOf(account);
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return _numCheckpoints(account);
}
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoints.Checkpoint208 memory) {
return _checkpoints(account, pos);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
import {SafeERC20} from "../utils/SafeERC20.sol";
import {IERC4626} from "../../../interfaces/IERC4626.sol";
import {Math} from "../../../utils/math/Math.sol";
/**
* @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
* The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
* and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
* itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
* offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
* of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
* With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
* underlying math can be found xref:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*/
abstract contract ERC4626 is ERC20, IERC4626 {
using Math for uint256;
IERC20 private immutable _asset;
uint8 private immutable _underlyingDecimals;
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
*/
constructor(IERC20 asset_) {
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
_underlyingDecimals = success ? assetDecimals : 18;
_asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool ok, uint8 assetDecimals) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeCall(IERC20Metadata.decimals, ())
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
return _underlyingDecimals + _decimalsOffset();
}
/** @dev See {IERC4626-asset}. */
function asset() public view virtual returns (address) {
return address(_asset);
}
/** @dev See {IERC4626-totalAssets}. */
function totalAssets() public view virtual returns (uint256) {
return _asset.balanceOf(address(this));
}
/** @dev See {IERC4626-convertToShares}. */
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-convertToAssets}. */
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxDeposit}. */
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxMint}. */
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxRedeem}. */
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-deposit}. */
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/** @dev See {IERC4626-mint}. */
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/** @dev See {IERC4626-withdraw}. */
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/** @dev See {IERC4626-redeem}. */
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
// If _asset is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If _asset is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20.safeTransfer(_asset, receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract Nonces {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
mapping(address account => uint256) private _nonces;
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
return _nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return _nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/types/Time.sol)
pragma solidity ^0.8.20;
import {Math} from "../math/Math.sol";
import {SafeCast} from "../math/SafeCast.sol";
/**
* @dev This library provides helpers for manipulating time-related objects.
*
* It uses the following types:
* - `uint48` for timepoints
* - `uint32` for durations
*
* While the library doesn't provide specific types for timepoints and duration, it does provide:
* - a `Delay` type to represent duration that can be programmed to change value automatically at a given point
* - additional helper functions
*/
library Time {
using Time for *;
/**
* @dev Get the block timestamp as a Timepoint.
*/
function timestamp() internal view returns (uint48) {
return SafeCast.toUint48(block.timestamp);
}
/**
* @dev Get the block number as a Timepoint.
*/
function blockNumber() internal view returns (uint48) {
return SafeCast.toUint48(block.number);
}
// ==================================================== Delay =====================================================
/**
* @dev A `Delay` is a uint32 duration that can be programmed to change value automatically at a given point in the
* future. The "effect" timepoint describes when the transitions happens from the "old" value to the "new" value.
* This allows updating the delay applied to some operation while keeping some guarantees.
*
* In particular, the {update} function guarantees that if the delay is reduced, the old delay still applies for
* some time. For example if the delay is currently 7 days to do an upgrade, the admin should not be able to set
* the delay to 0 and upgrade immediately. If the admin wants to reduce the delay, the old delay (7 days) should
* still apply for some time.
*
*
* The `Delay` type is 112 bits long, and packs the following:
*
* ```
* | [uint48]: effect date (timepoint)
* | | [uint32]: value before (duration)
* ↓ ↓ ↓ [uint32]: value after (duration)
* 0xAAAAAAAAAAAABBBBBBBBCCCCCCCC
* ```
*
* NOTE: The {get} and {withUpdate} functions operate using timestamps. Block number based delays are not currently
* supported.
*/
type Delay is uint112;
/**
* @dev Wrap a duration into a Delay to add the one-step "update in the future" feature
*/
function toDelay(uint32 duration) internal pure returns (Delay) {
return Delay.wrap(duration);
}
/**
* @dev Get the value at a given timepoint plus the pending value and effect timepoint if there is a scheduled
* change after this timepoint. If the effect timepoint is 0, then the pending value should not be considered.
*/
function _getFullAt(
Delay self,
uint48 timepoint
) private pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
(valueBefore, valueAfter, effect) = self.unpack();
return effect <= timepoint ? (valueAfter, 0, 0) : (valueBefore, valueAfter, effect);
}
/**
* @dev Get the current value plus the pending value and effect timepoint if there is a scheduled change. If the
* effect timepoint is 0, then the pending value should not be considered.
*/
function getFull(Delay self) internal view returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
return _getFullAt(self, timestamp());
}
/**
* @dev Get the current value.
*/
function get(Delay self) internal view returns (uint32) {
(uint32 delay, , ) = self.getFull();
return delay;
}
/**
* @dev Update a Delay object so that it takes a new duration after a timepoint that is automatically computed to
* enforce the old delay at the moment of the update. Returns the updated Delay object and the timestamp when the
* new delay becomes effective.
*/
function withUpdate(
Delay self,
uint32 newValue,
uint32 minSetback
) internal view returns (Delay updatedDelay, uint48 effect) {
uint32 value = self.get();
uint32 setback = uint32(Math.max(minSetback, value > newValue ? value - newValue : 0));
effect = timestamp() + setback;
return (pack(value, newValue, effect), effect);
}
/**
* @dev Split a delay into its components: valueBefore, valueAfter and effect (transition timepoint).
*/
function unpack(Delay self) internal pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
uint112 raw = Delay.unwrap(self);
valueAfter = uint32(raw);
valueBefore = uint32(raw >> 32);
effect = uint48(raw >> 64);
return (valueBefore, valueAfter, effect);
}
/**
* @dev pack the components into a Delay object.
*/
function pack(uint32 valueBefore, uint32 valueAfter, uint48 effect) internal pure returns (Delay) {
return Delay.wrap((uint112(effect) << 64) | (uint112(valueBefore) << 32) | uint112(valueAfter));
}
}// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; /* ██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗ ██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║ ██████╔╝██████╔╝██████╔╝██╔████╔██║███████║ ██║ ███████║ ██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║ ██║ ██╔══██║ ██║ ██║ ██║██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ██╗ ██╗██████╗ ██████╗ ██████╗ ██╗ ██╗ ██╗ █████╗ ██║ ██║██╔══██╗██╔════╝ ██╔═████╗╚██╗██╔╝███║██╔══██╗ ██║ ██║██║ ██║███████╗ ██║██╔██║ ╚███╔╝ ╚██║╚█████╔╝ ██║ ██║██║ ██║██╔═══██╗████╔╝██║ ██╔██╗ ██║██╔══██╗ ╚██████╔╝██████╔╝╚██████╔╝╚██████╔╝██╔╝ ██╗ ██║╚█████╔╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ */ import "./ud60x18/Casting.sol"; import "./ud60x18/Constants.sol"; import "./ud60x18/Conversions.sol"; import "./ud60x18/Errors.sol"; import "./ud60x18/Helpers.sol"; import "./ud60x18/Math.sol"; import "./ud60x18/ValueType.sol";
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { IERC4626 } from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title UnstakingManager
* @author akshatmittal, julianmrodri, pmckelvy1, tbrent
*/
contract UnstakingManager {
IERC20 public immutable targetToken;
IERC4626 public immutable vault;
struct Lock {
address user;
uint256 amount; // {targetToken}
uint256 unlockTime; // {s}
uint256 claimedAt; // {s}
}
uint256 private nextLockId;
mapping(uint256 => Lock) public locks;
event LockCreated(uint256 lockId, address user, uint256 amount, uint256 unlockTime);
event LockCancelled(uint256 lockId);
event LockClaimed(uint256 lockId);
error UnstakingManager__Unauthorized();
error UnstakingManager__NotUnlockedYet();
error UnstakingManager__AlreadyClaimed();
constructor(IERC20 _asset) {
targetToken = _asset;
vault = IERC4626(msg.sender);
}
/// @param amount {targetToken}
/// @param unlockTime {s}
function createLock(address user, uint256 amount, uint256 unlockTime) external {
require(msg.sender == address(vault), UnstakingManager__Unauthorized());
SafeERC20.safeTransferFrom(targetToken, msg.sender, address(this), amount);
uint256 lockId = nextLockId++;
Lock storage lock = locks[lockId];
lock.user = user;
lock.amount = amount;
lock.unlockTime = unlockTime;
emit LockCreated(lockId, user, amount, unlockTime);
}
function cancelLock(uint256 lockId) external {
Lock storage lock = locks[lockId];
require(lock.user == msg.sender, UnstakingManager__Unauthorized());
require(lock.claimedAt == 0, UnstakingManager__AlreadyClaimed());
SafeERC20.forceApprove(targetToken, address(vault), lock.amount);
vault.deposit(lock.amount, lock.user);
emit LockCancelled(lockId);
delete locks[lockId];
}
function claimLock(uint256 lockId) external {
Lock storage lock = locks[lockId];
require(lock.unlockTime <= block.timestamp && lock.unlockTime != 0, UnstakingManager__NotUnlockedYet());
require(lock.claimedAt == 0, UnstakingManager__AlreadyClaimed());
lock.claimedAt = block.timestamp;
SafeERC20.safeTransfer(targetToken, lock.user, lock.amount);
emit LockClaimed(lockId);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/IAccessControlEnumerable.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "../IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC-165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// 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;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.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.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)
}
}
}// 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
pragma solidity ^0.8.19;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC1271 } from "@openzeppelin/contracts/interfaces/IERC1271.sol";
interface IBaseTrustedFiller is IERC1271 {
error BaseTrustedFiller__SwapActive();
function initialize(
address _creator,
IERC20 _sellToken,
IERC20 _buyToken,
uint256 _sellAmount,
uint256 _minBuyAmount
) external;
function buyToken() external view returns (IERC20);
function sellToken() external view returns (IERC20);
function sellAmount() external view returns (uint256);
function swapActive() external view returns (bool);
function closeFiller() external;
function rescueToken(IERC20 token) external;
function setPartiallyFillable(bool _partiallyFillable) external;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// Optional bidder interface for callback
interface IBidderCallee {
/// @param buyAmount {buyTok}
function bidCallback(address buyToken, uint256 buyAmount, bytes calldata data) external;
}// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; /* ██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗ ██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║ ██████╔╝██████╔╝██████╔╝██╔████╔██║███████║ ██║ ███████║ ██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║ ██║ ██╔══██║ ██║ ██║ ██║██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ███████╗██████╗ ███████╗ █████╗ ██╗ ██╗ ██╗ █████╗ ██╔════╝██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝███║██╔══██╗ ███████╗██║ ██║███████╗╚██████║ ╚███╔╝ ╚██║╚█████╔╝ ╚════██║██║ ██║╚════██║ ╚═══██║ ██╔██╗ ██║██╔══██╗ ███████║██████╔╝███████║ █████╔╝██╔╝ ██╗ ██║╚█████╔╝ ╚══════╝╚═════╝ ╚══════╝ ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ */ import "./sd59x18/Casting.sol"; import "./sd59x18/Constants.sol"; import "./sd59x18/Conversions.sol"; import "./sd59x18/Errors.sol"; import "./sd59x18/Helpers.sol"; import "./sd59x18/Math.sol"; import "./sd59x18/ValueType.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/transparent/ProxyAdmin.sol)
pragma solidity ^0.8.20;
import {ITransparentUpgradeableProxy} from "./TransparentUpgradeableProxy.sol";
import {Ownable} from "../../access/Ownable.sol";
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address,address)`
* and `upgradeAndCall(address,address,bytes)` are present, and `upgrade` must be used if no function should be called,
* while `upgradeAndCall` will invoke the `receive` function if the third argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeAndCall(address,address,bytes)` is present, and the third argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev Sets the initial owner who can perform upgrades.
*/
constructor(address initialOwner) Ownable(initialOwner) {}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.
* See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
* - If `data` is empty, `msg.value` must be zero.
*/
function upgradeAndCall(
ITransparentUpgradeableProxy proxy,
address implementation,
bytes memory data
) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}// 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) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.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/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: By default this function reads _name which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Name() internal view returns (string memory) {
return _name.toStringWithFallback(_nameFallback);
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: By default this function reads _version which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Version() internal view returns (string memory) {
return _version.toStringWithFallback(_versionFallback);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (governance/utils/Votes.sol)
pragma solidity ^0.8.20;
import {IERC5805} from "../../interfaces/IERC5805.sol";
import {Context} from "../../utils/Context.sol";
import {Nonces} from "../../utils/Nonces.sol";
import {EIP712} from "../../utils/cryptography/EIP712.sol";
import {Checkpoints} from "../../utils/structs/Checkpoints.sol";
import {SafeCast} from "../../utils/math/SafeCast.sol";
import {ECDSA} from "../../utils/cryptography/ECDSA.sol";
import {Time} from "../../utils/types/Time.sol";
/**
* @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be
* transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of
* "representative" that will pool delegated voting units from different accounts and can then use it to vote in
* decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to
* delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.
*
* This contract is often combined with a token contract such that voting units correspond to token units. For an
* example, see {ERC721Votes}.
*
* The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed
* at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the
* cost of this history tracking optional.
*
* When using this module the derived contract must implement {_getVotingUnits} (for example, make it return
* {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the
* previous example, it would be included in {ERC721-_update}).
*/
abstract contract Votes is Context, EIP712, Nonces, IERC5805 {
using Checkpoints for Checkpoints.Trace208;
bytes32 private constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address account => address) private _delegatee;
mapping(address delegatee => Checkpoints.Trace208) private _delegateCheckpoints;
Checkpoints.Trace208 private _totalCheckpoints;
/**
* @dev The clock was incorrectly modified.
*/
error ERC6372InconsistentClock();
/**
* @dev Lookup to future votes is not available.
*/
error ERC5805FutureLookup(uint256 timepoint, uint48 clock);
/**
* @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based
* checkpoints (and voting), in which case {CLOCK_MODE} should be overridden as well to match.
*/
function clock() public view virtual returns (uint48) {
return Time.blockNumber();
}
/**
* @dev Machine-readable description of the clock as specified in ERC-6372.
*/
// solhint-disable-next-line func-name-mixedcase
function CLOCK_MODE() public view virtual returns (string memory) {
// Check that the clock was not modified
if (clock() != Time.blockNumber()) {
revert ERC6372InconsistentClock();
}
return "mode=blocknumber&from=default";
}
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) public view virtual returns (uint256) {
return _delegateCheckpoints[account].latest();
}
/**
* @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
* configured to use block numbers, this will return the value at the end of the corresponding block.
*
* Requirements:
*
* - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.
*/
function getPastVotes(address account, uint256 timepoint) public view virtual returns (uint256) {
uint48 currentTimepoint = clock();
if (timepoint >= currentTimepoint) {
revert ERC5805FutureLookup(timepoint, currentTimepoint);
}
return _delegateCheckpoints[account].upperLookupRecent(SafeCast.toUint48(timepoint));
}
/**
* @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
* configured to use block numbers, this will return the value at the end of the corresponding block.
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*
* Requirements:
*
* - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.
*/
function getPastTotalSupply(uint256 timepoint) public view virtual returns (uint256) {
uint48 currentTimepoint = clock();
if (timepoint >= currentTimepoint) {
revert ERC5805FutureLookup(timepoint, currentTimepoint);
}
return _totalCheckpoints.upperLookupRecent(SafeCast.toUint48(timepoint));
}
/**
* @dev Returns the current total supply of votes.
*/
function _getTotalSupply() internal view virtual returns (uint256) {
return _totalCheckpoints.latest();
}
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) public view virtual returns (address) {
return _delegatee[account];
}
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
address account = _msgSender();
_delegate(account, delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > expiry) {
revert VotesExpiredSignature(expiry);
}
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
_useCheckedNonce(signer, nonce);
_delegate(signer, delegatee);
}
/**
* @dev Delegate all of `account`'s voting units to `delegatee`.
*
* Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
*/
function _delegate(address account, address delegatee) internal virtual {
address oldDelegate = delegates(account);
_delegatee[account] = delegatee;
emit DelegateChanged(account, oldDelegate, delegatee);
_moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
}
/**
* @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`
* should be zero. Total supply of voting units will be adjusted with mints and burns.
*/
function _transferVotingUnits(address from, address to, uint256 amount) internal virtual {
if (from == address(0)) {
_push(_totalCheckpoints, _add, SafeCast.toUint208(amount));
}
if (to == address(0)) {
_push(_totalCheckpoints, _subtract, SafeCast.toUint208(amount));
}
_moveDelegateVotes(delegates(from), delegates(to), amount);
}
/**
* @dev Moves delegated votes from one delegate to another.
*/
function _moveDelegateVotes(address from, address to, uint256 amount) internal virtual {
if (from != to && amount > 0) {
if (from != address(0)) {
(uint256 oldValue, uint256 newValue) = _push(
_delegateCheckpoints[from],
_subtract,
SafeCast.toUint208(amount)
);
emit DelegateVotesChanged(from, oldValue, newValue);
}
if (to != address(0)) {
(uint256 oldValue, uint256 newValue) = _push(
_delegateCheckpoints[to],
_add,
SafeCast.toUint208(amount)
);
emit DelegateVotesChanged(to, oldValue, newValue);
}
}
}
/**
* @dev Get number of checkpoints for `account`.
*/
function _numCheckpoints(address account) internal view virtual returns (uint32) {
return SafeCast.toUint32(_delegateCheckpoints[account].length());
}
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function _checkpoints(
address account,
uint32 pos
) internal view virtual returns (Checkpoints.Checkpoint208 memory) {
return _delegateCheckpoints[account].at(pos);
}
function _push(
Checkpoints.Trace208 storage store,
function(uint208, uint208) view returns (uint208) op,
uint208 delta
) private returns (uint208 oldValue, uint208 newValue) {
return store.push(clock(), op(store.latest(), delta));
}
function _add(uint208 a, uint208 b) private pure returns (uint208) {
return a + b;
}
function _subtract(uint208 a, uint208 b) private pure returns (uint208) {
return a - b;
}
/**
* @dev Must return the voting units held by an account.
*/
function _getVotingUnits(address) internal view virtual returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/Checkpoints.sol)
// This file was procedurally generated from scripts/generate/templates/Checkpoints.js.
pragma solidity ^0.8.20;
import {Math} from "../math/Math.sol";
/**
* @dev This library defines the `Trace*` struct, for checkpointing values as they change at different points in
* time, and later looking up past values by block number. See {Votes} as an example.
*
* To create a history of checkpoints define a variable type `Checkpoints.Trace*` in your contract, and store a new
* checkpoint for the current transaction block using the {push} function.
*/
library Checkpoints {
/**
* @dev A value was attempted to be inserted on a past checkpoint.
*/
error CheckpointUnorderedInsertion();
struct Trace224 {
Checkpoint224[] _checkpoints;
}
struct Checkpoint224 {
uint32 _key;
uint224 _value;
}
/**
* @dev Pushes a (`key`, `value`) pair into a Trace224 so that it is stored as the checkpoint.
*
* Returns previous value and new value.
*
* IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint32).max` key set will disable the
* library.
*/
function push(
Trace224 storage self,
uint32 key,
uint224 value
) internal returns (uint224 oldValue, uint224 newValue) {
return _insert(self._checkpoints, key, value);
}
/**
* @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if
* there is none.
*/
function lowerLookup(Trace224 storage self, uint32 key) internal view returns (uint224) {
uint256 len = self._checkpoints.length;
uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);
return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*/
function upperLookup(Trace224 storage self, uint32 key) internal view returns (uint224) {
uint256 len = self._checkpoints.length;
uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*
* NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high
* keys).
*/
function upperLookupRecent(Trace224 storage self, uint32 key) internal view returns (uint224) {
uint256 len = self._checkpoints.length;
uint256 low = 0;
uint256 high = len;
if (len > 5) {
uint256 mid = len - Math.sqrt(len);
if (key < _unsafeAccess(self._checkpoints, mid)._key) {
high = mid;
} else {
low = mid + 1;
}
}
uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
*/
function latest(Trace224 storage self) internal view returns (uint224) {
uint256 pos = self._checkpoints.length;
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value
* in the most recent checkpoint.
*/
function latestCheckpoint(Trace224 storage self) internal view returns (bool exists, uint32 _key, uint224 _value) {
uint256 pos = self._checkpoints.length;
if (pos == 0) {
return (false, 0, 0);
} else {
Checkpoint224 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);
return (true, ckpt._key, ckpt._value);
}
}
/**
* @dev Returns the number of checkpoint.
*/
function length(Trace224 storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
/**
* @dev Returns checkpoint at given position.
*/
function at(Trace224 storage self, uint32 pos) internal view returns (Checkpoint224 memory) {
return self._checkpoints[pos];
}
/**
* @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
* or by updating the last one.
*/
function _insert(
Checkpoint224[] storage self,
uint32 key,
uint224 value
) private returns (uint224 oldValue, uint224 newValue) {
uint256 pos = self.length;
if (pos > 0) {
Checkpoint224 storage last = _unsafeAccess(self, pos - 1);
uint32 lastKey = last._key;
uint224 lastValue = last._value;
// Checkpoint keys must be non-decreasing.
if (lastKey > key) {
revert CheckpointUnorderedInsertion();
}
// Update or push new checkpoint
if (lastKey == key) {
last._value = value;
} else {
self.push(Checkpoint224({_key: key, _value: value}));
}
return (lastValue, value);
} else {
self.push(Checkpoint224({_key: key, _value: value}));
return (0, value);
}
}
/**
* @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _upperBinaryLookup(
Checkpoint224[] storage self,
uint32 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key > key) {
high = mid;
} else {
low = mid + 1;
}
}
return high;
}
/**
* @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _lowerBinaryLookup(
Checkpoint224[] storage self,
uint32 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key < key) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
/**
* @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
*/
function _unsafeAccess(
Checkpoint224[] storage self,
uint256 pos
) private pure returns (Checkpoint224 storage result) {
assembly {
mstore(0, self.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
struct Trace208 {
Checkpoint208[] _checkpoints;
}
struct Checkpoint208 {
uint48 _key;
uint208 _value;
}
/**
* @dev Pushes a (`key`, `value`) pair into a Trace208 so that it is stored as the checkpoint.
*
* Returns previous value and new value.
*
* IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint48).max` key set will disable the
* library.
*/
function push(
Trace208 storage self,
uint48 key,
uint208 value
) internal returns (uint208 oldValue, uint208 newValue) {
return _insert(self._checkpoints, key, value);
}
/**
* @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if
* there is none.
*/
function lowerLookup(Trace208 storage self, uint48 key) internal view returns (uint208) {
uint256 len = self._checkpoints.length;
uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);
return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*/
function upperLookup(Trace208 storage self, uint48 key) internal view returns (uint208) {
uint256 len = self._checkpoints.length;
uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*
* NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high
* keys).
*/
function upperLookupRecent(Trace208 storage self, uint48 key) internal view returns (uint208) {
uint256 len = self._checkpoints.length;
uint256 low = 0;
uint256 high = len;
if (len > 5) {
uint256 mid = len - Math.sqrt(len);
if (key < _unsafeAccess(self._checkpoints, mid)._key) {
high = mid;
} else {
low = mid + 1;
}
}
uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
*/
function latest(Trace208 storage self) internal view returns (uint208) {
uint256 pos = self._checkpoints.length;
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value
* in the most recent checkpoint.
*/
function latestCheckpoint(Trace208 storage self) internal view returns (bool exists, uint48 _key, uint208 _value) {
uint256 pos = self._checkpoints.length;
if (pos == 0) {
return (false, 0, 0);
} else {
Checkpoint208 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);
return (true, ckpt._key, ckpt._value);
}
}
/**
* @dev Returns the number of checkpoint.
*/
function length(Trace208 storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
/**
* @dev Returns checkpoint at given position.
*/
function at(Trace208 storage self, uint32 pos) internal view returns (Checkpoint208 memory) {
return self._checkpoints[pos];
}
/**
* @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
* or by updating the last one.
*/
function _insert(
Checkpoint208[] storage self,
uint48 key,
uint208 value
) private returns (uint208 oldValue, uint208 newValue) {
uint256 pos = self.length;
if (pos > 0) {
Checkpoint208 storage last = _unsafeAccess(self, pos - 1);
uint48 lastKey = last._key;
uint208 lastValue = last._value;
// Checkpoint keys must be non-decreasing.
if (lastKey > key) {
revert CheckpointUnorderedInsertion();
}
// Update or push new checkpoint
if (lastKey == key) {
last._value = value;
} else {
self.push(Checkpoint208({_key: key, _value: value}));
}
return (lastValue, value);
} else {
self.push(Checkpoint208({_key: key, _value: value}));
return (0, value);
}
}
/**
* @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _upperBinaryLookup(
Checkpoint208[] storage self,
uint48 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key > key) {
high = mid;
} else {
low = mid + 1;
}
}
return high;
}
/**
* @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _lowerBinaryLookup(
Checkpoint208[] storage self,
uint48 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key < key) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
/**
* @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
*/
function _unsafeAccess(
Checkpoint208[] storage self,
uint256 pos
) private pure returns (Checkpoint208 storage result) {
assembly {
mstore(0, self.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
struct Trace160 {
Checkpoint160[] _checkpoints;
}
struct Checkpoint160 {
uint96 _key;
uint160 _value;
}
/**
* @dev Pushes a (`key`, `value`) pair into a Trace160 so that it is stored as the checkpoint.
*
* Returns previous value and new value.
*
* IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint96).max` key set will disable the
* library.
*/
function push(
Trace160 storage self,
uint96 key,
uint160 value
) internal returns (uint160 oldValue, uint160 newValue) {
return _insert(self._checkpoints, key, value);
}
/**
* @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if
* there is none.
*/
function lowerLookup(Trace160 storage self, uint96 key) internal view returns (uint160) {
uint256 len = self._checkpoints.length;
uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);
return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*/
function upperLookup(Trace160 storage self, uint96 key) internal view returns (uint160) {
uint256 len = self._checkpoints.length;
uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*
* NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high
* keys).
*/
function upperLookupRecent(Trace160 storage self, uint96 key) internal view returns (uint160) {
uint256 len = self._checkpoints.length;
uint256 low = 0;
uint256 high = len;
if (len > 5) {
uint256 mid = len - Math.sqrt(len);
if (key < _unsafeAccess(self._checkpoints, mid)._key) {
high = mid;
} else {
low = mid + 1;
}
}
uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
*/
function latest(Trace160 storage self) internal view returns (uint160) {
uint256 pos = self._checkpoints.length;
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value
* in the most recent checkpoint.
*/
function latestCheckpoint(Trace160 storage self) internal view returns (bool exists, uint96 _key, uint160 _value) {
uint256 pos = self._checkpoints.length;
if (pos == 0) {
return (false, 0, 0);
} else {
Checkpoint160 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);
return (true, ckpt._key, ckpt._value);
}
}
/**
* @dev Returns the number of checkpoint.
*/
function length(Trace160 storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
/**
* @dev Returns checkpoint at given position.
*/
function at(Trace160 storage self, uint32 pos) internal view returns (Checkpoint160 memory) {
return self._checkpoints[pos];
}
/**
* @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
* or by updating the last one.
*/
function _insert(
Checkpoint160[] storage self,
uint96 key,
uint160 value
) private returns (uint160 oldValue, uint160 newValue) {
uint256 pos = self.length;
if (pos > 0) {
Checkpoint160 storage last = _unsafeAccess(self, pos - 1);
uint96 lastKey = last._key;
uint160 lastValue = last._value;
// Checkpoint keys must be non-decreasing.
if (lastKey > key) {
revert CheckpointUnorderedInsertion();
}
// Update or push new checkpoint
if (lastKey == key) {
last._value = value;
} else {
self.push(Checkpoint160({_key: key, _value: value}));
}
return (lastValue, value);
} else {
self.push(Checkpoint160({_key: key, _value: value}));
return (0, value);
}
}
/**
* @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _upperBinaryLookup(
Checkpoint160[] storage self,
uint96 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key > key) {
high = mid;
} else {
low = mid + 1;
}
}
return high;
}
/**
* @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _lowerBinaryLookup(
Checkpoint160[] storage self,
uint96 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key < key) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
/**
* @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
*/
function _unsafeAccess(
Checkpoint160[] storage self,
uint256 pos
) private pure returns (Checkpoint160 storage result) {
assembly {
mstore(0, self.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Casts a UD60x18 number into SD1x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD1x18
function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD1x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(uint64(xUint)));
}
/// @notice Casts a UD60x18 number into SD21x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD21x18
function intoSD21x18(UD60x18 x) pure returns (SD21x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD21x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD21x18_Overflow(x);
}
result = SD21x18.wrap(int128(uint128(xUint)));
}
/// @notice Casts a UD60x18 number into UD2x18.
/// @dev Requirements:
/// - x ≤ uMAX_UD2x18
function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD2x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(xUint));
}
/// @notice Casts a UD60x18 number into UD21x18.
/// @dev Requirements:
/// - x ≤ uMAX_UD21x18
function intoUD21x18(UD60x18 x) pure returns (UD21x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD21x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD21x18_Overflow(x);
}
result = UD21x18.wrap(uint128(xUint));
}
/// @notice Casts a UD60x18 number into SD59x18.
/// @dev Requirements:
/// - x ≤ uMAX_SD59x18
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(uMAX_SD59x18)) {
revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x);
}
result = SD59x18.wrap(int256(xUint));
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint256(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev Requirements:
/// - x ≤ MAX_UINT128
function intoUint128(UD60x18 x) pure returns (uint128 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT128) {
revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x);
}
result = uint128(xUint);
}
/// @notice Casts a UD60x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD60x18 x) pure returns (uint40 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT40) {
revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Alias for {wrap}.
function ud60x18(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Unwraps a UD60x18 number into uint256.
function unwrap(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Wraps a uint256 number into the UD60x18 value type.
function wrap(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as a UD60x18 number.
UD60x18 constant E = UD60x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
uint256 constant uEXP_MAX_INPUT = 133_084258667509499440;
UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT);
/// @dev The maximum input permitted in {exp2}.
uint256 constant uEXP2_MAX_INPUT = 192e18 - 1;
UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT);
/// @dev Half the UNIT number.
uint256 constant uHALF_UNIT = 0.5e18;
UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as a UD60x18 number.
uint256 constant uLOG2_10 = 3_321928094887362347;
UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as a UD60x18 number.
uint256 constant uLOG2_E = 1_442695040888963407;
UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);
/// @dev The maximum value a UD60x18 number can have.
uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);
/// @dev The maximum whole value a UD60x18 number can have.
uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);
/// @dev PI as a UD60x18 number.
UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD60x18.
uint256 constant uUNIT = 1e18;
UD60x18 constant UNIT = UD60x18.wrap(uUNIT);
/// @dev The unit number squared.
uint256 constant uUNIT_SQUARED = 1e36;
UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED);
/// @dev Zero as a UD60x18 number.
UD60x18 constant ZERO = UD60x18.wrap(0);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { uMAX_UD60x18, uUNIT } from "./Constants.sol";
import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Converts a UD60x18 number to a simple integer by dividing it by `UNIT`.
/// @dev The result is rounded toward zero.
/// @param x The UD60x18 number to convert.
/// @return result The same number in basic integer form.
function convert(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x) / uUNIT;
}
/// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x ≤ MAX_UD60x18 / UNIT
///
/// @param x The basic integer to convert.
/// @return result The same number converted to UD60x18.
function convert(uint256 x) pure returns (UD60x18 result) {
if (x > uMAX_UD60x18 / uUNIT) {
revert PRBMath_UD60x18_Convert_Overflow(x);
}
unchecked {
result = UD60x18.wrap(x * uUNIT);
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
/// @notice Thrown when ceiling a number overflows UD60x18.
error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18.
error PRBMath_UD60x18_Convert_Overflow(uint256 x);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD21x18.
error PRBMath_UD60x18_IntoSD21x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18.
error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD21x18.
error PRBMath_UD60x18_IntoUD21x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);
/// @notice Thrown when taking the logarithm of a number less than UNIT.
error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);
/// @notice Thrown when calculating the square root overflows UD60x18.
error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the UD60x18 type.
function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal operation (==) in the UD60x18 type.
function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the UD60x18 type.
function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the UD60x18 type.
function isZero(UD60x18 x) pure returns (bool result) {
// This wouldn't work if x could be negative.
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the UD60x18 type.
function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the UD60x18 type.
function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the checked modulo operation (%) in the UD60x18 type.
function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the UD60x18 type.
function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the UD60x18 type.
function not(UD60x18 x) pure returns (UD60x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the UD60x18 type.
function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { wrap } from "./Casting.sol";
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_UD60x18,
uMAX_WHOLE_UD60x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { UD60x18 } from "./ValueType.sol";
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the arithmetic average of x and y using the following formula:
///
/// $$
/// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
/// $$
///
/// In English, this is what this formula does:
///
/// 1. AND x and y.
/// 2. Calculate half of XOR x and y.
/// 3. Add the two results together.
///
/// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
/// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The arithmetic average as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
unchecked {
result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev This is optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≤ MAX_WHOLE_UD60x18
///
/// @param x The UD60x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint > uMAX_WHOLE_UD60x18) {
revert Errors.PRBMath_UD60x18_Ceil_Overflow(x);
}
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `UNIT - remainder`.
let delta := sub(uUNIT, remainder)
// Equivalent to `x + remainder > 0 ? delta : 0`.
result := add(x, mul(delta, gt(remainder, 0)))
}
}
/// @notice Divides two UD60x18 numbers, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @param x The numerator as a UD60x18 number.
/// @param y The denominator as a UD60x18 number.
/// @return result The quotient as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap()));
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Requirements:
/// - x ≤ 133_084258667509499440
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xUint > uEXP_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
uint256 doubleUnitProduct = xUint * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693
///
/// Requirements:
/// - x < 192e18
/// - The result must fit in UD60x18.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xUint > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x);
}
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = (xUint << 64) / uUNIT;
// Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation.
result = wrap(Common.exp2(x_192x64));
}
/// @notice Yields the greatest whole number less than or equal to x.
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The UD60x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `x - remainder > 0 ? remainder : 0)`.
result := sub(x, mul(remainder, gt(remainder, 0)))
}
}
/// @notice Yields the excess beyond the floor of x using the odd function definition.
/// @dev See https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The UD60x18 number to get the fractional part of.
/// @return result The fractional part of x as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function frac(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
result := mod(x, uUNIT)
}
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down.
///
/// @dev Requirements:
/// - x * y must fit in UD60x18.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
if (xUint == 0 || yUint == 0) {
return ZERO;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xyUint = xUint * yUint;
if (xyUint / xUint != yUint) {
revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
result = wrap(Common.sqrt(xyUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The UD60x18 number for which to calculate the inverse.
/// @return result The inverse as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~196_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
default { result := uMAX_UD60x18 }
}
if (result.unwrap() == uMAX_UD60x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x ≥ UNIT
///
/// @param x The UD60x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
unchecked {
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(xUint / uUNIT);
// This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because n
// n is at most 255 and UNIT is 1e18.
uint256 resultUint = n * uUNIT;
// Calculate $y = x * 2^{-n}$.
uint256 y = xUint >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultUint);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
uint256 DOUBLE_UNIT = 2e18;
for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= DOUBLE_UNIT) {
// Add the 2^{-m} factor to the logarithm.
resultUint += delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
result = wrap(resultUint);
}
}
/// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @dev See the documentation in {Common.mulDiv18}.
/// @param x The multiplicand as a UD60x18 number.
/// @param y The multiplier as a UD60x18 number.
/// @return result The product as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap()));
}
/// @notice Raises x to the power of y.
///
/// For $1 \leq x \leq \infty$, the following standard formula is used:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used:
///
/// $$
/// i = \frac{1}{x}
/// w = 2^{log_2{i} * y}
/// x^y = \frac{1}{w}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2} and {mul}.
/// - Returns `UNIT` for 0^0.
/// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xUint == 0) {
return yUint == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xUint == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yUint == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yUint == uUNIT) {
return x;
}
// If x is > UNIT, use the standard formula.
if (xUint > uUNIT) {
result = exp2(mul(log2(x), y));
}
// Conversely, if x < UNIT, use the equivalent formula.
else {
UD60x18 i = wrap(uUNIT_SQUARED / xUint);
UD60x18 w = exp2(mul(log2(i), y));
result = wrap(uUNIT_SQUARED / w.unwrap());
}
}
/// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - The result must fit in UD60x18.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
// Calculate the first iteration of the loop in advance.
uint256 xUint = x.unwrap();
uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
for (y >>= 1; y > 0; y >>= 1) {
xUint = Common.mulDiv18(xUint, xUint);
// Equivalent to `y % 2 == 1`.
if (y & 1 > 0) {
resultUint = Common.mulDiv18(resultUint, xUint);
}
}
result = wrap(resultUint);
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x ≤ MAX_UD60x18 / UNIT
///
/// @param x The UD60x18 number for which to calculate the square root.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
unchecked {
if (xUint > uMAX_UD60x18 / uUNIT) {
revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x);
}
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers.
// In this case, the two numbers are both the square root.
result = wrap(Common.sqrt(xUint * uUNIT));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
/// @dev The value type is defined here so it can be imported in all other files.
type UD60x18 is uint256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD1x18,
Casting.intoSD21x18,
Casting.intoSD59x18,
Casting.intoUD2x18,
Casting.intoUD21x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.ln,
Math.log10,
Math.log2,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.xor
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the UD60x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.or as |,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.sub as -,
Helpers.xor as ^
} for UD60x18 global;// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// 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
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18, uMIN_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Casts an SD59x18 number into int256.
/// @dev This is basically a functional alias for {unwrap}.
function intoInt256(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Casts an SD59x18 number into SD1x18.
/// @dev Requirements:
/// - x ≥ uMIN_SD1x18
/// - x ≤ uMAX_SD1x18
function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x);
}
if (xInt > uMAX_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(xInt));
}
/// @notice Casts an SD59x18 number into SD21x18.
/// @dev Requirements:
/// - x ≥ uMIN_SD21x18
/// - x ≤ uMAX_SD21x18
function intoSD21x18(SD59x18 x) pure returns (SD21x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD21x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Underflow(x);
}
if (xInt > uMAX_SD21x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Overflow(x);
}
result = SD21x18.wrap(int128(xInt));
}
/// @notice Casts an SD59x18 number into UD2x18.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UD2x18
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD2x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD21x18.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UD21x18
function intoUD21x18(SD59x18 x) pure returns (UD21x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD21x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Overflow(x);
}
result = UD21x18.wrap(uint128(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD59x18 x) pure returns (uint256 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x);
}
result = uint256(xInt);
}
/// @notice Casts an SD59x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ uMAX_UINT128
function intoUint128(SD59x18 x) pure returns (uint128 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT128))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x);
}
result = uint128(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD59x18 x) pure returns (uint40 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT40))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x);
}
result = uint40(uint256(xInt));
}
/// @notice Alias for {wrap}.
function sd(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Alias for {wrap}.
function sd59x18(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Unwraps an SD59x18 number into int256.
function unwrap(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Wraps an int256 number into SD59x18.
function wrap(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as an SD59x18 number.
SD59x18 constant E = SD59x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
int256 constant uEXP_MAX_INPUT = 133_084258667509499440;
SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT);
/// @dev Any value less than this returns 0 in {exp}.
int256 constant uEXP_MIN_THRESHOLD = -41_446531673892822322;
SD59x18 constant EXP_MIN_THRESHOLD = SD59x18.wrap(uEXP_MIN_THRESHOLD);
/// @dev The maximum input permitted in {exp2}.
int256 constant uEXP2_MAX_INPUT = 192e18 - 1;
SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT);
/// @dev Any value less than this returns 0 in {exp2}.
int256 constant uEXP2_MIN_THRESHOLD = -59_794705707972522261;
SD59x18 constant EXP2_MIN_THRESHOLD = SD59x18.wrap(uEXP2_MIN_THRESHOLD);
/// @dev Half the UNIT number.
int256 constant uHALF_UNIT = 0.5e18;
SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as an SD59x18 number.
int256 constant uLOG2_10 = 3_321928094887362347;
SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as an SD59x18 number.
int256 constant uLOG2_E = 1_442695040888963407;
SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);
/// @dev The maximum value an SD59x18 number can have.
int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);
/// @dev The maximum whole value an SD59x18 number can have.
int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);
/// @dev The minimum value an SD59x18 number can have.
int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);
/// @dev The minimum whole value an SD59x18 number can have.
int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);
/// @dev PI as an SD59x18 number.
SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD59x18.
int256 constant uUNIT = 1e18;
SD59x18 constant UNIT = SD59x18.wrap(1e18);
/// @dev The unit number squared.
int256 constant uUNIT_SQUARED = 1e36;
SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED);
/// @dev Zero as an SD59x18 number.
SD59x18 constant ZERO = SD59x18.wrap(0);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { uMAX_SD59x18, uMIN_SD59x18, uUNIT } from "./Constants.sol";
import { PRBMath_SD59x18_Convert_Overflow, PRBMath_SD59x18_Convert_Underflow } from "./Errors.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Converts a simple integer to SD59x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x ≥ `MIN_SD59x18 / UNIT`
/// - x ≤ `MAX_SD59x18 / UNIT`
///
/// @param x The basic integer to convert.
/// @return result The same number converted to SD59x18.
function convert(int256 x) pure returns (SD59x18 result) {
if (x < uMIN_SD59x18 / uUNIT) {
revert PRBMath_SD59x18_Convert_Underflow(x);
}
if (x > uMAX_SD59x18 / uUNIT) {
revert PRBMath_SD59x18_Convert_Overflow(x);
}
unchecked {
result = SD59x18.wrap(x * uUNIT);
}
}
/// @notice Converts an SD59x18 number to a simple integer by dividing it by `UNIT`.
/// @dev The result is rounded toward zero.
/// @param x The SD59x18 number to convert.
/// @return result The same number as a simple integer.
function convert(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x) / uUNIT;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
/// @notice Thrown when taking the absolute value of `MIN_SD59x18`.
error PRBMath_SD59x18_Abs_MinSD59x18();
/// @notice Thrown when ceiling a number overflows SD59x18.
error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMath_SD59x18_Convert_Overflow(int256 x);
/// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMath_SD59x18_Convert_Underflow(int256 x);
/// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`.
error PRBMath_SD59x18_Div_InputTooSmall();
/// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);
/// @notice Thrown when flooring a number underflows SD59x18.
error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and their product is negative.
error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD60x18.
error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint256.
error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);
/// @notice Thrown when taking the logarithm of a number less than or equal to zero.
error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);
/// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
error PRBMath_SD59x18_Mul_InputTooSmall();
/// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when raising a number to a power and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);
/// @notice Thrown when taking the square root of a negative number.
error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);
/// @notice Thrown when the calculating the square root overflows SD59x18.
error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the SD59x18 type.
function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
return wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal (=) operation in the SD59x18 type.
function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the SD59x18 type.
function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the SD59x18 type.
function isZero(SD59x18 x) pure returns (bool result) {
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the SD59x18 type.
function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the SD59x18 type.
function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the SD59x18 type.
function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the SD59x18 type.
function not(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the SD59x18 type.
function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the checked unary minus operation (-) in the SD59x18 type.
function unary(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(-x.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
unchecked {
result = wrap(-x.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uEXP_MIN_THRESHOLD,
uEXP2_MIN_THRESHOLD,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_SD59x18,
uMAX_WHOLE_SD59x18,
uMIN_SD59x18,
uMIN_WHOLE_SD59x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { wrap } from "./Helpers.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Calculates the absolute value of x.
///
/// @dev Requirements:
/// - x > MIN_SD59x18.
///
/// @param x The SD59x18 number for which to calculate the absolute value.
/// @return result The absolute value of x as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function abs(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Abs_MinSD59x18();
}
result = xInt < 0 ? wrap(-xInt) : x;
}
/// @notice Calculates the arithmetic average of x and y.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The arithmetic average as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
unchecked {
// This operation is equivalent to `x / 2 + y / 2`, and it can never overflow.
int256 sum = (xInt >> 1) + (yInt >> 1);
if (sum < 0) {
// If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right
// rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`.
assembly ("memory-safe") {
result := add(sum, and(or(xInt, yInt), 1))
}
} else {
// Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting.
result = wrap(sum + (xInt & yInt & 1));
}
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≤ MAX_WHOLE_SD59x18
///
/// @param x The SD59x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt > uMAX_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Ceil_Overflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt > 0) {
resultInt += uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Divides two SD59x18 numbers, returning a new SD59x18 number.
///
/// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute
/// values separately.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The denominator must not be zero.
/// - The result must fit in SD59x18.
///
/// @param x The numerator as an SD59x18 number.
/// @param y The denominator as an SD59x18 number.
/// @return result The quotient as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Div_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Div_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}.
///
/// Requirements:
/// - Refer to the requirements in {exp2}.
/// - x < 133_084258667509499441.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
// Any input less than the threshold returns zero.
// This check also prevents an overflow for very small numbers.
if (xInt < uEXP_MIN_THRESHOLD) {
return ZERO;
}
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xInt > uEXP_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
int256 doubleUnitProduct = xInt * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method using the following formula:
///
/// $$
/// 2^{-x} = \frac{1}{2^x}
/// $$
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Notes:
/// - If x < -59_794705707972522261, the result is zero.
///
/// Requirements:
/// - x < 192e18.
/// - The result must fit in SD59x18.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
// The inverse of any number less than the threshold is truncated to zero.
if (xInt < uEXP2_MIN_THRESHOLD) {
return ZERO;
}
unchecked {
// Inline the fixed-point inversion to save gas.
result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap());
}
} else {
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xInt > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = uint256((xInt << 64) / uUNIT);
// It is safe to cast the result to int256 due to the checks above.
result = wrap(int256(Common.exp2(x_192x64)));
}
}
}
/// @notice Yields the greatest whole number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x ≥ MIN_WHOLE_SD59x18
///
/// @param x The SD59x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < uMIN_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Floor_Underflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt < 0) {
resultInt -= uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right.
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The SD59x18 number to get the fractional part of.
/// @return result The fractional part of x as an SD59x18 number.
function frac(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % uUNIT);
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x * y must fit in SD59x18.
/// - x * y must not be negative, since complex numbers are not supported.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == 0 || yInt == 0) {
return ZERO;
}
unchecked {
// Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it.
int256 xyInt = xInt * yInt;
if (xyInt / xInt != yInt) {
revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y);
}
// The product must not be negative, since complex numbers are not supported.
if (xyInt < 0) {
revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
uint256 resultUint = Common.sqrt(uint256(xyInt));
result = wrap(int256(resultUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The SD59x18 number for which to calculate the inverse.
/// @return result The inverse as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(SD59x18 x) pure returns (SD59x18 result) {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~195_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
default { result := uMAX_SD59x18 }
}
if (result.unwrap() == uMAX_SD59x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation.
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x > 0
///
/// @param x The SD59x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt <= 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
unchecked {
int256 sign;
if (xInt >= uUNIT) {
sign = 1;
} else {
sign = -1;
// Inline the fixed-point inversion to save gas.
xInt = uUNIT_SQUARED / xInt;
}
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(uint256(xInt / uUNIT));
// This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
// because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1.
int256 resultInt = int256(n) * uUNIT;
// Calculate $y = x * 2^{-n}$.
int256 y = xInt >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultInt * sign);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
int256 DOUBLE_UNIT = 2e18;
for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= DOUBLE_UNIT) {
// Add the 2^{-m} factor to the logarithm.
resultInt = resultInt + delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
resultInt *= sign;
result = wrap(resultInt);
}
}
/// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
///
/// @dev Notes:
/// - Refer to the notes in {Common.mulDiv18}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv18}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The result must fit in SD59x18.
///
/// @param x The multiplicand as an SD59x18 number.
/// @param y The multiplier as an SD59x18 number.
/// @return result The product as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Mul_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv18(xAbs, yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Raises x to the power of y using the following formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}, {log2}, and {mul}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as an SD59x18 number.
/// @param y Exponent to raise x to, as an SD59x18 number
/// @return result x raised to power y, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xInt == 0) {
return yInt == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xInt == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yInt == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yInt == uUNIT) {
return x;
}
// Calculate the result using the formula.
result = exp2(mul(log2(x), y));
}
/// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {abs} and {Common.mulDiv18}.
/// - The result must fit in SD59x18.
///
/// @param x The base as an SD59x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
uint256 xAbs = uint256(abs(x).unwrap());
// Calculate the first iteration of the loop in advance.
uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = Common.mulDiv18(xAbs, xAbs);
// Equivalent to `y % 2 == 1`.
if (yAux & 1 > 0) {
resultAbs = Common.mulDiv18(resultAbs, xAbs);
}
}
// The result must fit in SD59x18.
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y);
}
unchecked {
// Is the base negative and the exponent odd? If yes, the result should be negative.
int256 resultInt = int256(resultAbs);
bool isNegative = x.unwrap() < 0 && y & 1 == 1;
if (isNegative) {
resultInt = -resultInt;
}
result = wrap(resultInt);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - Only the positive root is returned.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x ≥ 0, since complex numbers are not supported.
/// - x ≤ MAX_SD59x18 / UNIT
///
/// @param x The SD59x18 number for which to calculate the square root.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x);
}
if (xInt > uMAX_SD59x18 / uUNIT) {
revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x);
}
unchecked {
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers.
// In this case, the two numbers are both the square root.
uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT));
result = wrap(int256(resultUint));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int256.
type SD59x18 is int256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoInt256,
Casting.intoSD1x18,
Casting.intoSD21x18,
Casting.intoUD2x18,
Casting.intoUD21x18,
Casting.intoUD60x18,
Casting.intoUint256,
Casting.intoUint128,
Casting.intoUint40,
Casting.unwrap
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Math.abs,
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.log10,
Math.log2,
Math.ln,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.uncheckedUnary,
Helpers.xor
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the SD59x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.or as |,
Helpers.sub as -,
Helpers.unary as -,
Helpers.xor as ^
} for SD59x18 global;// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}// 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/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
assembly ("memory-safe") {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5805.sol)
pragma solidity ^0.8.20;
import {IVotes} from "../governance/utils/IVotes.sol";
import {IERC6372} from "./IERC6372.sol";
interface IERC5805 is IERC6372, IVotes {}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
// Common.sol
//
// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.
/*//////////////////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);
/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);
/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();
/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;
/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;
/// @dev The maximum value a uint64 number can have.
uint64 constant MAX_UINT64 = type(uint64).max;
/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;
/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;
/*//////////////////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
//
// 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
// 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
// a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
// we know that `x & 0xFF` is also 1.
if (x & 0xFF00000000000000 > 0) {
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
}
if (x & 0xFF000000000000 > 0) {
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
}
if (x & 0xFF0000000000 > 0) {
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
}
if (x & 0xFF00000000 > 0) {
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
}
if (x & 0xFF000000 > 0) {
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
}
if (x & 0xFF0000 > 0) {
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
}
if (x & 0xFF00 > 0) {
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
}
if (x & 0xFF > 0) {
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
}
// In the code snippet below, two operations are executed simultaneously:
//
// 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
// accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
// 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
//
// The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
// integer part, $2^n$.
result *= UNIT;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
/// x >>= 128;
/// result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
// 2^128
assembly ("memory-safe") {
let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^64
assembly ("memory-safe") {
let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^32
assembly ("memory-safe") {
let factor := shl(5, gt(x, 0xFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^16
assembly ("memory-safe") {
let factor := shl(4, gt(x, 0xFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^8
assembly ("memory-safe") {
let factor := shl(3, gt(x, 0xFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^4
assembly ("memory-safe") {
let factor := shl(2, gt(x, 0xF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^2
assembly ("memory-safe") {
let factor := shl(1, gt(x, 0x3))
x := shr(factor, x)
result := or(result, factor)
}
// 2^1
// No need to shift x any more.
assembly ("memory-safe") {
let factor := gt(x, 0x1)
result := or(result, factor)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
return prod0 / denominator;
}
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath_MulDiv_Overflow(x, y, denominator);
}
////////////////////////////////////////////////////////////////////////////
// 512 by 256 division
////////////////////////////////////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using the mulmod Yul instruction.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512-bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
unchecked {
// Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
// because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
// For more detail, see https://cs.stackexchange.com/q/138556/92363.
uint256 lpotdod = denominator & (~denominator + 1);
uint256 flippedLpotdod;
assembly ("memory-safe") {
// Factor powers of two out of denominator.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
// `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
// However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * flippedLpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
}
}
/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
/// x * y = MAX\_UINT256 * UNIT \\
/// (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
unchecked {
return prod0 / UNIT;
}
}
if (prod1 >= UNIT) {
revert PRBMath_MulDiv18_Overflow(x, y);
}
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(x, y, UNIT)
result :=
mul(
or(
div(sub(prod0, remainder), UNIT_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
),
UNIT_INVERSE
)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath_MulDivSigned_InputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 xAbs;
uint256 yAbs;
uint256 dAbs;
unchecked {
xAbs = x < 0 ? uint256(-x) : uint256(x);
yAbs = y < 0 ? uint256(-y) : uint256(y);
dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of x*y÷denominator. The result must fit in int256.
uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
if (resultAbs > uint256(type(int256).max)) {
revert PRBMath_MulDivSigned_Overflow(x, y);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly ("memory-safe") {
// "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
// If there are, the result should be negative. Otherwise, it should be positive.
unchecked {
result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
//
// We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
//
// $$
// msb(x) <= x <= 2*msb(x)$
// $$
//
// We write $msb(x)$ as $2^k$, and we get:
//
// $$
// k = log_2(x)
// $$
//
// Thus, we can write the initial inequality as:
//
// $$
// 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
// sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
// 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
// $$
//
// Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 2 ** 128) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 2 ** 64) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 2 ** 32) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 2 ** 16) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 2 ** 8) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 2 ** 4) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 2 ** 2) {
result <<= 1;
}
// At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
// most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision
// doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of
// precision into the expected uint128 result.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
// If x is not a perfect square, round the result toward zero.
uint256 roundedResult = x / result;
if (result >= roundedResult) {
result = roundedResult;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD1x18 number.
SD1x18 constant E = SD1x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD1x18 number can have.
int64 constant uMAX_SD1x18 = 9_223372036854775807;
SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);
/// @dev The minimum value an SD1x18 number can have.
int64 constant uMIN_SD1x18 = -9_223372036854775808;
SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);
/// @dev PI as an SD1x18 number.
SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD1x18.
SD1x18 constant UNIT = SD1x18.wrap(1e18);
int64 constant uUNIT = 1e18;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD1x18 is int64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for SD1x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD21x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD21x18 number.
SD21x18 constant E = SD21x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD21x18 number can have.
int128 constant uMAX_SD21x18 = 170141183460469231731_687303715884105727;
SD21x18 constant MAX_SD21x18 = SD21x18.wrap(uMAX_SD21x18);
/// @dev The minimum value an SD21x18 number can have.
int128 constant uMIN_SD21x18 = -170141183460469231731_687303715884105728;
SD21x18 constant MIN_SD21x18 = SD21x18.wrap(uMIN_SD21x18);
/// @dev PI as an SD21x18 number.
SD21x18 constant PI = SD21x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD21x18.
SD21x18 constant UNIT = SD21x18.wrap(1e18);
int128 constant uUNIT = 1e18;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int128. This is useful when end users want to use int128 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD21x18 is int128;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for SD21x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD2x18 number.
UD2x18 constant E = UD2x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD2x18 number can have.
uint64 constant uMAX_UD2x18 = 18_446744073709551615;
UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);
/// @dev PI as a UD2x18 number.
UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD2x18.
UD2x18 constant UNIT = UD2x18.wrap(1e18);
uint64 constant uUNIT = 1e18;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD21x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD21x18 number.
UD21x18 constant E = UD21x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD21x18 number can have.
uint128 constant uMAX_UD21x18 = 340282366920938463463_374607431768211455;
UD21x18 constant MAX_UD21x18 = UD21x18.wrap(uMAX_UD21x18);
/// @dev PI as a UD21x18 number.
UD21x18 constant PI = UD21x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD21x18.
uint256 constant uUNIT = 1e18;
UD21x18 constant UNIT = UD21x18.wrap(1e18);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD2x18 is uint64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD2x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint128. This is useful when end users want to use uint128 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD21x18 is uint128;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD21x18 global;// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
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));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC6372.sol)
pragma solidity ^0.8.20;
interface IERC6372 {
/**
* @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
*/
function clock() external view returns (uint48);
/**
* @dev Description of the clock
*/
// solhint-disable-next-line func-name-mixedcase
function CLOCK_MODE() external view returns (string memory);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD1x18 } from "./ValueType.sol";
/// @notice Casts an SD1x18 number into SD59x18.
/// @dev There is no overflow check because SD1x18 ⊆ SD59x18.
function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
}
/// @notice Casts an SD1x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
function intoUint128(SD1x18 x) pure returns (uint128 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x);
}
result = uint128(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD1x18 x) pure returns (uint256 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x);
}
result = uint256(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD1x18 x) pure returns (uint40 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x);
}
if (xInt > int64(uint64(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x);
}
result = uint40(uint64(xInt));
}
/// @notice Alias for {wrap}.
function sd1x18(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}
/// @notice Unwraps an SD1x18 number into int64.
function unwrap(SD1x18 x) pure returns (int64 result) {
result = SD1x18.unwrap(x);
}
/// @notice Wraps an int64 number into SD1x18.
function wrap(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD21x18 } from "./ValueType.sol";
/// @notice Casts an SD21x18 number into SD59x18.
/// @dev There is no overflow check because SD21x18 ⊆ SD59x18.
function intoSD59x18(SD21x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD21x18.unwrap(x)));
}
/// @notice Casts an SD21x18 number into UD60x18.
/// @dev Requirements:
/// - x ≥ 0
function intoUD60x18(SD21x18 x) pure returns (UD60x18 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint128(xInt));
}
/// @notice Casts an SD21x18 number into uint128.
/// @dev Requirements:
/// - x ≥ 0
function intoUint128(SD21x18 x) pure returns (uint128 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint128_Underflow(x);
}
result = uint128(xInt);
}
/// @notice Casts an SD21x18 number into uint256.
/// @dev Requirements:
/// - x ≥ 0
function intoUint256(SD21x18 x) pure returns (uint256 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint256_Underflow(x);
}
result = uint256(uint128(xInt));
}
/// @notice Casts an SD21x18 number into uint40.
/// @dev Requirements:
/// - x ≥ 0
/// - x ≤ MAX_UINT40
function intoUint40(SD21x18 x) pure returns (uint40 result) {
int128 xInt = SD21x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD21x18_ToUint40_Underflow(x);
}
if (xInt > int128(uint128(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD21x18_ToUint40_Overflow(x);
}
result = uint40(uint128(xInt));
}
/// @notice Alias for {wrap}.
function sd21x18(int128 x) pure returns (SD21x18 result) {
result = SD21x18.wrap(x);
}
/// @notice Unwraps an SD21x18 number into int128.
function unwrap(SD21x18 x) pure returns (int128 result) {
result = SD21x18.unwrap(x);
}
/// @notice Wraps an int128 number into SD21x18.
function wrap(int128 x) pure returns (SD21x18 result) {
result = SD21x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD2x18 } from "./ValueType.sol";
/// @notice Casts a UD2x18 number into SD59x18.
/// @dev There is no overflow check because UD2x18 ⊆ SD59x18.
function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
}
/// @notice Casts a UD2x18 number into UD60x18.
/// @dev There is no overflow check because UD2x18 ⊆ UD60x18.
function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint128.
/// @dev There is no overflow check because UD2x18 ⊆ uint128.
function intoUint128(UD2x18 x) pure returns (uint128 result) {
result = uint128(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint256.
/// @dev There is no overflow check because UD2x18 ⊆ uint256.
function intoUint256(UD2x18 x) pure returns (uint256 result) {
result = uint256(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD2x18 x) pure returns (uint40 result) {
uint64 xUint = UD2x18.unwrap(x);
if (xUint > uint64(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud2x18(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}
/// @notice Unwrap a UD2x18 number into uint64.
function unwrap(UD2x18 x) pure returns (uint64 result) {
result = UD2x18.unwrap(x);
}
/// @notice Wraps a uint64 number into UD2x18.
function wrap(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD21x18 } from "./ValueType.sol";
/// @notice Casts a UD21x18 number into SD59x18.
/// @dev There is no overflow check because UD21x18 ⊆ SD59x18.
function intoSD59x18(UD21x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD21x18.unwrap(x))));
}
/// @notice Casts a UD21x18 number into UD60x18.
/// @dev There is no overflow check because UD21x18 ⊆ UD60x18.
function intoUD60x18(UD21x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD21x18.unwrap(x));
}
/// @notice Casts a UD21x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint128(UD21x18 x) pure returns (uint128 result) {
result = UD21x18.unwrap(x);
}
/// @notice Casts a UD21x18 number into uint256.
/// @dev There is no overflow check because UD21x18 ⊆ uint256.
function intoUint256(UD21x18 x) pure returns (uint256 result) {
result = uint256(UD21x18.unwrap(x));
}
/// @notice Casts a UD21x18 number into uint40.
/// @dev Requirements:
/// - x ≤ MAX_UINT40
function intoUint40(UD21x18 x) pure returns (uint40 result) {
uint128 xUint = UD21x18.unwrap(x);
if (xUint > uint128(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD21x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud21x18(uint128 x) pure returns (UD21x18 result) {
result = UD21x18.wrap(x);
}
/// @notice Unwrap a UD21x18 number into uint128.
function unwrap(UD21x18 x) pure returns (uint128 result) {
result = UD21x18.unwrap(x);
}
/// @notice Wraps a uint128 number into UD21x18.
function wrap(uint128 x) pure returns (UD21x18 result) {
result = UD21x18.wrap(x);
}// 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.19;
import { SD1x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in UD60x18.
error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint128.
error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint256.
error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);
/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD21x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint128.
error PRBMath_SD21x18_ToUint128_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in UD60x18.
error PRBMath_SD21x18_ToUD60x18_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint256.
error PRBMath_SD21x18_ToUint256_Underflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Overflow(SD21x18 x);
/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Underflow(SD21x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40.
error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD21x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD21x18 number that doesn't fit in uint40.
error PRBMath_UD21x18_IntoUint40_Overflow(UD21x18 x);{
"remappings": [
"forge-std/=node_modules/forge-std/src/",
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"@reserve-protocol/trusted-fillers/=node_modules/@reserve-protocol/trusted-fillers/",
"@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
"@prb/math/=node_modules/@prb/math/",
"utils/=test/utils/",
"@src/=contracts/",
"@utils/=contracts/utils/",
"@interfaces/=contracts/interfaces/",
"@folio/=contracts/folio/",
"@gov/=contracts/governance/",
"@staking/=contracts/staking/",
"@deployer/=contracts/deployer/",
"@spells/=contracts/spells/",
"@periphery/=contracts/periphery/",
"@cowprotocol/=node_modules/@cowprotocol/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "none",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "paris",
"viaIR": false,
"libraries": {
"contracts/deployer/FolioDeployer.sol": {
"MathLib": "0x1d84718cf856c82e71499ec02c8b52a392b8fce3",
"RebalancingLib": "0xcaf303d82520bec16a1615538212985787c9a02a"
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_daoFeeRegistry","type":"address"},{"internalType":"address","name":"_versionRegistry","type":"address"},{"internalType":"address","name":"_trustedFillerRegistry","type":"address"},{"internalType":"contract IGovernanceDeployer","name":"_governanceDeployer","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"FolioDeployer__LengthMismatch","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"folioOwner","type":"address"},{"indexed":true,"internalType":"address","name":"folio","type":"address"},{"indexed":false,"internalType":"address","name":"folioAdmin","type":"address"}],"name":"FolioDeployed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"stToken","type":"address"},{"indexed":true,"internalType":"address","name":"folio","type":"address"},{"indexed":false,"internalType":"address","name":"ownerGovernor","type":"address"},{"indexed":false,"internalType":"address","name":"ownerTimelock","type":"address"},{"indexed":false,"internalType":"address","name":"tradingGovernor","type":"address"},{"indexed":false,"internalType":"address","name":"tradingTimelock","type":"address"}],"name":"GovernedFolioDeployed","type":"event"},{"inputs":[],"name":"daoFeeRegistry","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"address[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"uint256","name":"initialShares","type":"uint256"}],"internalType":"struct IFolio.FolioBasicDetails","name":"basicDetails","type":"tuple"},{"components":[{"internalType":"uint256","name":"auctionLength","type":"uint256"},{"components":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint96","name":"portion","type":"uint96"}],"internalType":"struct IFolio.FeeRecipient[]","name":"feeRecipients","type":"tuple[]"},{"internalType":"uint256","name":"tvlFee","type":"uint256"},{"internalType":"uint256","name":"mintFee","type":"uint256"},{"internalType":"string","name":"mandate","type":"string"}],"internalType":"struct IFolio.FolioAdditionalDetails","name":"additionalDetails","type":"tuple"},{"components":[{"internalType":"bool","name":"trustedFillerEnabled","type":"bool"},{"components":[{"internalType":"bool","name":"weightControl","type":"bool"},{"internalType":"enum IFolio.PriceControl","name":"priceControl","type":"uint8"}],"internalType":"struct IFolio.RebalanceControl","name":"rebalanceControl","type":"tuple"},{"internalType":"bool","name":"bidsEnabled","type":"bool"}],"internalType":"struct IFolio.FolioFlags","name":"folioFlags","type":"tuple"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"address[]","name":"basketManagers","type":"address[]"},{"internalType":"address[]","name":"auctionLaunchers","type":"address[]"},{"internalType":"address[]","name":"brandManagers","type":"address[]"},{"internalType":"bytes32","name":"deploymentNonce","type":"bytes32"}],"name":"deployFolio","outputs":[{"internalType":"contract Folio","name":"folio","type":"address"},{"internalType":"address","name":"proxyAdmin","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IVotes","name":"stToken","type":"address"},{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"address[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"uint256","name":"initialShares","type":"uint256"}],"internalType":"struct IFolio.FolioBasicDetails","name":"basicDetails","type":"tuple"},{"components":[{"internalType":"uint256","name":"auctionLength","type":"uint256"},{"components":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint96","name":"portion","type":"uint96"}],"internalType":"struct IFolio.FeeRecipient[]","name":"feeRecipients","type":"tuple[]"},{"internalType":"uint256","name":"tvlFee","type":"uint256"},{"internalType":"uint256","name":"mintFee","type":"uint256"},{"internalType":"string","name":"mandate","type":"string"}],"internalType":"struct IFolio.FolioAdditionalDetails","name":"additionalDetails","type":"tuple"},{"components":[{"internalType":"bool","name":"trustedFillerEnabled","type":"bool"},{"components":[{"internalType":"bool","name":"weightControl","type":"bool"},{"internalType":"enum IFolio.PriceControl","name":"priceControl","type":"uint8"}],"internalType":"struct IFolio.RebalanceControl","name":"rebalanceControl","type":"tuple"},{"internalType":"bool","name":"bidsEnabled","type":"bool"}],"internalType":"struct IFolio.FolioFlags","name":"folioFlags","type":"tuple"},{"components":[{"internalType":"uint48","name":"votingDelay","type":"uint48"},{"internalType":"uint32","name":"votingPeriod","type":"uint32"},{"internalType":"uint256","name":"proposalThreshold","type":"uint256"},{"internalType":"uint256","name":"quorumThreshold","type":"uint256"},{"internalType":"uint256","name":"timelockDelay","type":"uint256"},{"internalType":"address[]","name":"guardians","type":"address[]"}],"internalType":"struct IGovernanceDeployer.GovParams","name":"ownerGovParams","type":"tuple"},{"components":[{"internalType":"uint48","name":"votingDelay","type":"uint48"},{"internalType":"uint32","name":"votingPeriod","type":"uint32"},{"internalType":"uint256","name":"proposalThreshold","type":"uint256"},{"internalType":"uint256","name":"quorumThreshold","type":"uint256"},{"internalType":"uint256","name":"timelockDelay","type":"uint256"},{"internalType":"address[]","name":"guardians","type":"address[]"}],"internalType":"struct IGovernanceDeployer.GovParams","name":"tradingGovParams","type":"tuple"},{"components":[{"internalType":"address[]","name":"existingBasketManagers","type":"address[]"},{"internalType":"address[]","name":"auctionLaunchers","type":"address[]"},{"internalType":"address[]","name":"brandManagers","type":"address[]"}],"internalType":"struct IFolioDeployer.GovRoles","name":"govRoles","type":"tuple"},{"internalType":"bytes32","name":"deploymentNonce","type":"bytes32"}],"name":"deployGovernedFolio","outputs":[{"internalType":"contract Folio","name":"folio","type":"address"},{"internalType":"address","name":"proxyAdmin","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"folioImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"governanceDeployer","outputs":[{"internalType":"contract IGovernanceDeployer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"trustedFillerRegistry","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"versionRegistry","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]Contract Creation Code
61012060405234801561001157600080fd5b50604051618b57380380618b57833981016040819052610030916100b3565b6001600160a01b0380851660a052838116608052821660c0526040516100559061008e565b604051809103906000f080158015610071573d6000803e3d6000fd5b506001600160a01b0390811660e052166101005250610112915050565b615e8180612cd683390190565b6001600160a01b03811681146100b057600080fd5b50565b600080600080608085870312156100c957600080fd5b84516100d48161009b565b60208601519094506100e58161009b565b60408601519093506100f68161009b565b60608601519092506101078161009b565b939692955090935050565b60805160a05160c05160e05161010051612b51610185600039600081816092015281816103310152818161046c01526105610152600081816101b80152610aa301526000818160d60152610bc601526000818161017e0152610ba10152600081816101240152610a3b0152612b516000f3fe608060405234801561001057600080fd5b50600436106100885760003560e01c806371b0a1091161005b57806371b0a109146101465780639980cb2314610179578063a5e39e8e146101a0578063c42f3d1b146101b357600080fd5b806305111eb91461008d57806321903d79146100d157806354fd4d50146100f8578063608935151461011f575b600080fd5b6100b47f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b6100b47f000000000000000000000000000000000000000000000000000000000000000081565b60408051808201825260058152640352e302e360dc1b602082015290516100c891906111c6565b6100b47f000000000000000000000000000000000000000000000000000000000000000081565b610159610154366004611256565b6101da565b604080516001600160a01b039384168152929091166020830152016100c8565b6100b47f000000000000000000000000000000000000000000000000000000000000000081565b6101596101ae366004611428565b610989565b6100b47f000000000000000000000000000000000000000000000000000000000000000081565b60408051336020808301919091528183018490528251808303840181526060909201909252805191012060009081906102d18a8a8a3061021a8a80611526565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506102599250505060208c018c611526565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506102989250505060408d018d611526565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152508b9250610989915050565b6040805160028082526060820190925292955090935060009190816020015b60408051808201909152600080825260208201528152602001906001900390816102f05790505090506001600160a01b038c1661046a576001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001663c59ee4a96103608d80611576565b6040516020016103719291906115bc565b60408051601f1981840301815291905261038e60208f018f611576565b60405160200161039f9291906115e4565b604051602081830303815290604052878c876040518663ffffffff1660e01b81526004016103d195949392919061171b565b6060604051808303816000875af11580156103f0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104149190611776565b83600081518110610427576104276117c3565b602002602001015160000184600081518110610445576104456117c3565b6020908102919091018101516001600160a01b03938416910152911690529b5061054c565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663a7f52023898e856040518463ffffffff1660e01b81526004016104ba939291906117d9565b60408051808303816000875af11580156104d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104fc9190611807565b8260008151811061050f5761050f6117c3565b60200260200101516000018360008151811061052d5761052d6117c3565b6020908102919091018101516001600160a01b03938416910152911690525b6105568680611526565b905060000361070d577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663a7f52023888e85196040518463ffffffff1660e01b81526004016105b0939291906117d9565b60408051808303816000875af11580156105ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105f29190611807565b82600181518110610605576106056117c3565b602002602001015160000183600181518110610623576106236117c3565b6020026020010151602001826001600160a01b03166001600160a01b0316815250826001600160a01b03166001600160a01b03168152505050836001600160a01b0316632f2ff15d7f4ff6ae4d6a29e79ca45c6441bdc89b93878ac6118485b33c8baa3749fc3cb1308360018151811061069f5761069f6117c3565b6020026020010151602001516040518363ffffffff1660e01b81526004016106da9291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b1580156106f457600080fd5b505af1158015610708573d6000803e3d6000fd5b505050505b836001600160a01b0316632f2ff15d6000801b83600081518110610733576107336117c3565b6020026020010151602001516040518363ffffffff1660e01b815260040161076e9291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b15801561078857600080fd5b505af115801561079c573d6000803e3d6000fd5b5050604051631b2b455f60e11b8152600060048201523060248201526001600160a01b03871692506336568abe9150604401600060405180830381600087803b1580156107e857600080fd5b505af11580156107fc573d6000803e3d6000fd5b50505050826001600160a01b031663f2fde38b82600081518110610822576108226117c3565b6020026020010151602001516040518263ffffffff1660e01b815260040161085991906001600160a01b0391909116815260200190565b600060405180830381600087803b15801561087357600080fd5b505af1158015610887573d6000803e3d6000fd5b50505050836001600160a01b03168c6001600160a01b03167f08af36628654870563f8102f737700df4046cdfaef3ff1a7a48253d07e9e1a6b836000815181106108d3576108d36117c3565b602002602001015160000151846000815181106108f2576108f26117c3565b60200260200101516020015185600181518110610911576109116117c3565b60200260200101516000015186600181518110610930576109306117c3565b60200260200101516020015160405161097294939291906001600160a01b03948516815292841660208401529083166040830152909116606082015260800190565b60405180910390a350509850989650505050505050565b60008061099960608b018b611526565b90506109a860408c018c611526565b9050146109c857604051632692258760e11b815260040160405180910390fd5b6000338b8b8b8b8b8b8b6040516020016109e89796959493929190611b0e565b60408051601f1981840301815282825280516020918201206001600160a01b03909416908301528101919091526060810185905260800160405160208183030381529060405280519060200120905080887f0000000000000000000000000000000000000000000000000000000000000000604051610a6690611166565b6001600160a01b039283168152911660208201526040018190604051809103906000f5905080158015610a9d573d6000803e3d6000fd5b509150807f000000000000000000000000000000000000000000000000000000000000000083604051610acf90611173565b6001600160a01b039283168152911660208201526040018190604051809103906000f5905080158015610b06573d6000803e3d6000fd5b50925060005b610b1960408d018d611526565b9050811015610b8d57610b85610b3260408e018e611526565b83818110610b4257610b426117c3565b9050602002016020810190610b579190611b9d565b33868f8060600190610b699190611526565b86818110610b7957610b796117c3565b90506020020135611091565b600101610b0c565b506040805180820182526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811682527f0000000000000000000000000000000000000000000000000000000000000000811660208301529151632104725560e21b815291851691638411c95491610c16918f918f918f903390600401611bba565b600060405180830381600087803b158015610c3057600080fd5b505af1158015610c44573d6000803e3d6000fd5b50505050826001600160a01b0316632f2ff15d846001600160a01b031663a217fddf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cb99190611c2b565b6040516001600160e01b031960e084901b16815260048101919091526001600160a01b038b166024820152604401600060405180830381600087803b158015610d0157600080fd5b505af1158015610d15573d6000803e3d6000fd5b5050505060005b8751811015610ddc57836001600160a01b0316632f2ff15d7f4ff6ae4d6a29e79ca45c6441bdc89b93878ac6118485b33c8baa3749fc3cb1308a8481518110610d6757610d676117c3565b60200260200101516040518363ffffffff1660e01b8152600401610d9e9291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b158015610db857600080fd5b505af1158015610dcc573d6000803e3d6000fd5b505060019092019150610d1c9050565b5060005b8651811015610ea057836001600160a01b0316632f2ff15d7f13ff1b2625181b311f257c723b5e6d366eb318b212d9dd694c48fcf227659df5898481518110610e2b57610e2b6117c3565b60200260200101516040518363ffffffff1660e01b8152600401610e629291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b158015610e7c57600080fd5b505af1158015610e90573d6000803e3d6000fd5b505060019092019150610de09050565b5060005b8551811015610f6457836001600160a01b0316632f2ff15d7f2d8e650da9bd8c373ab2450d770f2ed39549bfc28d3630025cecc51511bcd374888481518110610eef57610eef6117c3565b60200260200101516040518363ffffffff1660e01b8152600401610f269291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b158015610f4057600080fd5b505af1158015610f54573d6000803e3d6000fd5b505060019092019150610ea49050565b506001600160a01b038816301461103e57826001600160a01b03166336568abe846001600160a01b031663a217fddf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610fc2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fe69190611c2b565b6040516001600160e01b031960e084901b1681526004810191909152306024820152604401600060405180830381600087803b15801561102557600080fd5b505af1158015611039573d6000803e3d6000fd5b505050505b6040516001600160a01b03838116825280851691908a16907f017464e04c545b4f5c5e32a4c60ce4ff586eef58fdda661784f9905bcd764fda9060200160405180910390a3509850989650505050505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b1790526110eb9085906110f1565b50505050565b600080602060008451602086016000885af180611114576040513d6000823e3d81fd5b50506000513d9150811561112c578060011415611139565b6001600160a01b0384163b155b156110eb57604051635274afe760e01b81526001600160a01b038516600482015260240160405180910390fd5b6106d480611c4583390190565b61082c8061231983390190565b6000815180845260005b818110156111a65760208185018101518683018201520161118a565b506000602082860101526020601f19601f83011685010191505092915050565b6020815260006111d96020830184611180565b9392505050565b6001600160a01b03811681146111f557600080fd5b50565b8035611203816111e0565b919050565b600060a0828403121561121a57600080fd5b50919050565b60006080828403121561121a57600080fd5b600060c0828403121561121a57600080fd5b60006060828403121561121a57600080fd5b600080600080600080600080610160898b03121561127357600080fd5b61127c896111f8565b975060208901356001600160401b0381111561129757600080fd5b6112a38b828c01611208565b97505060408901356001600160401b038111156112bf57600080fd5b6112cb8b828c01611208565b9650506112db8a60608b01611220565b945060e08901356001600160401b038111156112f657600080fd5b6113028b828c01611232565b9450506101008901356001600160401b0381111561131f57600080fd5b61132b8b828c01611232565b9350506101208901356001600160401b0381111561134857600080fd5b6113548b828c01611244565b989b979a5095989497939692955092936101400135925050565b634e487b7160e01b600052604160045260246000fd5b600082601f83011261139557600080fd5b81356001600160401b038111156113ae576113ae61136e565b8060051b604051601f19603f83011681018181106001600160401b03821117156113da576113da61136e565b6040529182526020818501810192908101868411156113f857600080fd5b6020860192505b8383101561141e57611410836111f8565b8152602092830192016113ff565b5095945050505050565b600080600080600080600080610160898b03121561144557600080fd5b88356001600160401b0381111561145b57600080fd5b6114678b828c01611208565b98505060208901356001600160401b0381111561148357600080fd5b61148f8b828c01611208565b97505061149f8a60408b01611220565b95506114ad60c08a016111f8565b945060e08901356001600160401b038111156114c857600080fd5b6114d48b828c01611384565b9450506101008901356001600160401b038111156114f157600080fd5b6114fd8b828c01611384565b9350506101208901356001600160401b0381111561151a57600080fd5b6113548b828c01611384565b6000808335601e1984360301811261153d57600080fd5b8301803591506001600160401b0382111561155757600080fd5b6020019150600581901b360382131561156f57600080fd5b9250929050565b6000808335601e1984360301811261158d57600080fd5b8301803591506001600160401b038211156115a757600080fd5b60200191503681900382131561156f57600080fd5b6b02b37ba3296a637b1b5b2b2160a51b81528183600c83013760009101600c01908152919050565b61159360f21b81528183600283013760009101600201908152919050565b6000808335601e1984360301811261161957600080fd5b83016020810192503590506001600160401b0381111561163857600080fd5b8060051b360382131561156f57600080fd5b81835260208301925060008160005b8481101561168a57813561166c816111e0565b6001600160a01b031686526020958601959190910190600101611659565b5093949350505050565b6000813565ffffffffffff81168082146116ad57600080fd5b845250602082013563ffffffff811681146116c757600080fd5b63ffffffff1660208401526040828101359084015260608083013590840152608080830135908401526116fd60a0830183611602565b60c060a086015261171260c08601828461164a565b95945050505050565b60a08152600061172e60a0830188611180565b82810360208401526117408188611180565b6001600160a01b0387166040850152838103606085015290506117638186611694565b9150508260808301529695505050505050565b60008060006060848603121561178b57600080fd5b8351611796816111e0565b60208501519093506117a7816111e0565b60408501519092506117b8816111e0565b809150509250925092565b634e487b7160e01b600052603260045260246000fd5b6060815260006117ec6060830186611694565b6001600160a01b039490941660208301525060400152919050565b6000806040838503121561181a57600080fd5b8251611825816111e0565b6020840151909250611836816111e0565b809150509250929050565b6000808335601e1984360301811261185857600080fd5b83016020810192503590506001600160401b0381111561187757600080fd5b80360382131561156f57600080fd5b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60006118bb8283611841565b60a085526118cd60a086018284611886565b9150506118dd6020840184611841565b85830360208701526118f0838284611886565b925050506119016040840184611602565b858303604087015261191483828461164a565b925050506119256060840184611602565b85830360608701528083526001600160fb1b0381111561194457600080fd5b60051b80826020850137608094850135959094019490945290910160200192915050565b81835260208301925060008160005b8481101561168a57813561198a816111e0565b6001600160a01b0316865260208201356bffffffffffffffffffffffff81168082146119b557600080fd5b6020880152506040958601959190910190600101611977565b803582526000602082013536839003601e190181126119ec57600080fd5b82016020810190356001600160401b03811115611a0857600080fd5b8060061b3603821315611a1a57600080fd5b60a06020860152611a2f60a086018284611968565b60408581013590870152606080860135908701529150611a5490506080840184611841565b8583036080870152611a67838284611886565b9695505050505050565b8035801515811461120357600080fd5b611a8a81611a71565b15158252611a9a60208201611a71565b15156020830152604081013560038110158015611ab657600080fd5b506040830152611ac860608201611a71565b151560608301525050565b600081518084526020840193506020830160005b8281101561168a5781516001600160a01b0316865260209586019590910190600101611ae7565b61014081526000611b2361014083018a6118af565b8281036020840152611b35818a6119ce565b9050611b446040840189611a81565b6001600160a01b03871660c084015282810360e0840152611b658187611ad3565b9050828103610100840152611b7a8186611ad3565b9050828103610120840152611b8f8185611ad3565b9a9950505050505050505050565b600060208284031215611baf57600080fd5b81356111d9816111e0565b61012081526000611bcf6101208301886118af565b8281036020840152611be181886119ce565b86516001600160a01b03908116604086015260208801511660608501529150611c0f90506080830185611a81565b6001600160a01b03929092166101009190910152949350505050565b600060208284031215611c3d57600080fd5b505191905056fe60a060405234801561001057600080fd5b506040516106d43803806106d483398101604081905261002f916100e6565b816001600160a01b03811661005e57604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b6100678161007a565b506001600160a01b031660805250610119565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b80516001600160a01b03811681146100e157600080fd5b919050565b600080604083850312156100f957600080fd5b610102836100ca565b9150610110602084016100ca565b90509250929050565b60805161059a61013a6000396000818160610152610111015261059a6000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c8063608935151461005c578063715018a61461009f57806386e5ab2e146100a95780638da5cb5b146100bc578063f2fde38b146100cd575b600080fd5b6100837f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200160405180910390f35b6100a76100e0565b005b6100a76100b73660046103f8565b6100f4565b6000546001600160a01b0316610083565b6100a76100db3660046104cd565b61030d565b6100e8610350565b6100f2600061037d565b565b6100fc610350565b6040516237935760e61b8152600481018390527f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b03821690630de4d5c090602401602060405180830381865afa158015610162573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061018691906104f1565b156101a45760405163639c421d60e01b815260040160405180910390fd5b604051633740401760e01b8152600481018490526000906001600160a01b03831690633740401790602401602060405180830381865afa1580156101ec573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102109190610513565b6001600160a01b0316036102375760405163a9146eeb60e01b815260040160405180910390fd5b604051632777202560e11b8152600481018490526000906001600160a01b03831690634eee404a90602401602060405180830381865afa15801561027f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102a39190610513565b60405163278f794360e11b81529091506001600160a01b03861690634f1ef286906102d49084908790600401610530565b600060405180830381600087803b1580156102ee57600080fd5b505af1158015610302573d6000803e3d6000fd5b505050505050505050565b610315610350565b6001600160a01b03811661034457604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b61034d8161037d565b50565b6000546001600160a01b031633146100f25760405163118cdaa760e01b815233600482015260240161033b565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b038116811461034d57600080fd5b634e487b7160e01b600052604160045260246000fd5b60008060006060848603121561040d57600080fd5b8335610418816103cd565b925060208401359150604084013567ffffffffffffffff81111561043b57600080fd5b8401601f8101861361044c57600080fd5b803567ffffffffffffffff811115610466576104666103e2565b604051601f8201601f19908116603f0116810167ffffffffffffffff81118282101715610495576104956103e2565b6040528181528282016020018810156104ad57600080fd5b816020840160208301376000602083830101528093505050509250925092565b6000602082840312156104df57600080fd5b81356104ea816103cd565b9392505050565b60006020828403121561050357600080fd5b815180151581146104ea57600080fd5b60006020828403121561052557600080fd5b81516104ea816103cd565b60018060a01b0383168152604060208201526000825180604084015260005b8181101561056c576020818601810151606086840101520161054f565b506000606082850101526060601f19601f830116840101915050939250505056fea164736f6c634300081c000a608060405234801561001057600080fd5b5060405161082c38038061082c83398101604081905261002f91610324565b604080516020810190915260008152829061004a828261005d565b506100569050816100bc565b5050610386565b6100668261012a565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a28051156100b0576100ab82826101a9565b505050565b6100b8610220565b5050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6100fc60008051602061080c833981519152546001600160a01b031690565b604080516001600160a01b03928316815291841660208301520160405180910390a161012781610241565b50565b806001600160a01b03163b60000361016557604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5b80546001600160a01b0319166001600160a01b039290921691909117905550565b6060600080846001600160a01b0316846040516101c69190610357565b600060405180830381855af49150503d8060008114610201576040519150601f19603f3d011682016040523d82523d6000602084013e610206565b606091505b509092509050610217858383610280565b95945050505050565b341561023f5760405163b398979f60e01b815260040160405180910390fd5b565b6001600160a01b03811661026b57604051633173bdd160e11b81526000600482015260240161015c565b8060008051602061080c833981519152610188565b60608261029557610290826102df565b6102d8565b81511580156102ac57506001600160a01b0384163b155b156102d557604051639996b31560e01b81526001600160a01b038516600482015260240161015c565b50805b9392505050565b8051156102ef5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b80516001600160a01b038116811461031f57600080fd5b919050565b6000806040838503121561033757600080fd5b61034083610308565b915061034e60208401610308565b90509250929050565b6000825160005b81811015610378576020818601810151858301520161035e565b506000920191825250919050565b610477806103956000396000f3fe608060405261000c61000e565b005b610016610091565b6001600160a01b03163303610087576000356001600160e01b03191663278f794360e11b14610058576040516334ad5dbb60e21b815260040160405180910390fd5b6000806100683660048184610323565b8101906100759190610363565b9150915061008382826100c4565b5050565b61008f61011f565b565b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b546001600160a01b0316919050565b6100cd8261012f565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a28051156101175761011282826101ab565b505050565b610083610221565b61008f61012a610240565b61024f565b806001600160a01b03163b60000361016a57604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060600080846001600160a01b0316846040516101c8919061043b565b600060405180830381855af49150503d8060008114610203576040519150601f19603f3d011682016040523d82523d6000602084013e610208565b606091505b5091509150610218858383610273565b95945050505050565b341561008f5760405163b398979f60e01b815260040160405180910390fd5b600061024a6102d2565b905090565b3660008037600080366000845af43d6000803e80801561026e573d6000f35b3d6000fd5b60608261028857610283826102fa565b6102cb565b815115801561029f57506001600160a01b0384163b155b156102c857604051639996b31560e01b81526001600160a01b0385166004820152602401610161565b50805b9392505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc6100b5565b80511561030a5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b6000808585111561033357600080fd5b8386111561034057600080fd5b5050820193919092039150565b634e487b7160e01b600052604160045260246000fd5b6000806040838503121561037657600080fd5b82356001600160a01b038116811461038d57600080fd5b9150602083013567ffffffffffffffff8111156103a957600080fd5b8301601f810185136103ba57600080fd5b803567ffffffffffffffff8111156103d4576103d461034d565b604051601f8201601f19908116603f0116810167ffffffffffffffff811182821017156104035761040361034d565b60405281815282820160200187101561041b57600080fd5b816020840160208301376000602083830101528093505050509250929050565b6000825160005b8181101561045c5760208186018101518583015201610442565b50600092019182525091905056fea164736f6c634300081c000ab53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103a164736f6c634300081c000a6080604052348015600f57600080fd5b506016601a565b60ca565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff161560695760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b039081161460c75780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b615da8806100d96000396000f3fe608060405234801561001057600080fd5b50600436106103ef5760003560e01c80637aeaafb311610215578063b0384a0b11610125578063ca15c873116100b8578063d547741f11610087578063d547741f14610900578063dd62ed3e14610913578063e1e7bd5914610926578063eddd0d9c14610939578063fc5284821461094c57600080fd5b8063ca15c873146108a3578063ce923605146108b6578063d17618bf146108c9578063d3ebe4ce146108dc57600080fd5b8063bd7379c7116100f4578063bd7379c714610866578063c47f00271461087a578063c4ec22ad1461088d578063c71782301461089657600080fd5b8063b0384a0b14610822578063b200deda14610842578063b579605b1461084b578063bb57ad201461085e57600080fd5b8063979d5094116101a85780639fa0bba4116101775780639fa0bba4146107ba578063a217fddf146107cd578063a3246ad3146107d5578063a9059cbb146107f5578063aa3b55681461080857600080fd5b8063979d5094146107785780639980cb23146107815780639dacba23146107945780639f200bba146107a757600080fd5b80638cdf1288116101e45780638cdf1288146107375780639010d07c1461074a57806391d148541461075d57806395d89b411461077057600080fd5b80637aeaafb314610701578063834e630f14610709578063836a1040146107115780638411c9541461072457600080fd5b80632f2ff15d11610310578063459cf24b116102a3578063571a26a011610272578063571a26a014610645578063591cb1fc1461068f57806370a08231146106af57806376990dcd146106e5578063783e93f0146106f857600080fd5b8063459cf24b146105be5780634b61ffeb146105cb57806351fe9eff146105ea57806354fd4d501461062457600080fd5b806336568abe116102df57806336568abe1461057d578063374cbb2c1461059057806339b1b96d146105a35780633c46570f146105ab57600080fd5b80632f2ff15d1461053f578063313ce56714610552578063320736bf14610561578063325c25a21461057457600080fd5b806318160ddd1161038857806321903d791161035757806321903d79146104db578063236ed8f31461050657806323b872dd14610519578063248a9ca31461052c57600080fd5b806318160ddd146104a557806318178358146104ad5780631fffacd8146104b5578063207c8eed146104c857600080fd5b806306fdde03116103c457806306fdde0314610453578063072c2f1714610468578063095ea7b31461048957806313966db51461049c57600080fd5b806240718e146103f45780624aaa39146103fe57806301e1d1141461041157806301ffc9a714610430575b600080fd5b6103fc610955565b005b6103fc61040c3660046149b6565b610a29565b610419610a41565b604051610427929190614a49565b60405180910390f35b61044361043e366004614a6e565b610a54565b6040519015158152602001610427565b61045b610a7f565b6040516104279190614a98565b61047b610476366004614ae6565b610b42565b604051908152602001610427565b610443610497366004614b14565b610ea5565b61047b60065481565b61047b610ebd565b6103fc610f14565b6103fc6104c3366004614b4e565b610f2c565b6103fc6104d6366004614b99565b610f46565b6012546104ee906001600160a01b031681565b6040516001600160a01b039091168152602001610427565b6103fc610514366004614ae6565b611088565b610443610527366004614c31565b611184565b61047b61053a366004614ae6565b6111aa565b6103fc61054d366004614c72565b6111cc565b60405160128152602001610427565b6104ee61056f366004614c97565b6111ee565b61047b600f5481565b6103fc61058b366004614c72565b611411565b6103fc61059e366004614cf2565b611444565b61045b611486565b61047b6105b9366004614d97565b611514565b6020546104439060ff1681565b6105d361174b565b604080519215158352901515602083015201610427565b6105fd6105f8366004614ae6565b61180e565b604080516001600160a01b0390931683526001600160601b03909116602083015201610427565b6040805180820190915260058152640352e302e360dc1b602082015261045b565b610674610653366004614ae6565b601e6020526000908152604090208054600282015460039092015490919083565b60408051938452602084019290925290820152606001610427565b6106a261069d366004614c72565b611849565b6040516104279190614e89565b61047b6106bd366004614cf2565b6001600160a01b03166000908152600080516020615d5c833981519152602052604090205490565b6106746106f3366004614ea0565b6118b4565b61047b60095481565b6103fc6118e6565b61047b611938565b61041961071f366004614ee8565b611955565b6103fc610732366004614f21565b611c00565b6103fc610745366004614cf2565b612079565b6104ee610758366004614fcd565b61216b565b61044361076b366004614c72565b61219a565b61045b6121d2565b61047b60085481565b6000546104ee906001600160a01b031681565b6103fc6107a2366004614fef565b612211565b6103fc6107b536600461504d565b612225565b6103fc6107c8366004614ae6565b61223a565b61047b600081565b6107e86107e3366004614ae6565b612256565b604051610427919061508e565b610443610803366004614b14565b612281565b61081061228f565b604051610427969594939291906150d9565b6108356108303660046151dc565b61248b565b604051610427919061526b565b61047b60055481565b6103fc610859366004614ae6565b612656565b6103fc612672565b60125461044390600160a01b900460ff1681565b6103fc61088836600461504d565b612883565b61047b60075481565b600a546104439060ff1681565b61047b6108b1366004614ae6565b612898565b61047b6108c436600461527e565b6128be565b6104196108d7366004615315565b6129ea565b6014546108f29060ff8082169161010090041682565b60405161042792919061533e565b6103fc61090e366004614c72565b612a03565b61047b610921366004615354565b612a1f565b6103fc610934366004615382565b612a69565b6103fc610947366004614ae6565b612a86565b61047b601f5481565b61095d612aa2565b61096860003361219a565b8061099857506109987f4ff6ae4d6a29e79ca45c6441bdc89b93878ac6118485b33c8baa3749fc3cb1303361219a565b806109c857506109c87f13ff1b2625181b311f257c723b5e6d366eb318b212d9dd694c48fcf227659df53361219a565b6109e557604051637bdeee5360e11b815260040160405180910390fd5b6015546040519081527f4413e35d9a55c68763294e889871b8e17c9650f0db8fcfaf50690b4b02c943709060200160405180910390a142601c55610a27612aec565b565b6000610a3481612b12565b610a3d82612b1c565b5050565b606080610a4c612b66565b915091509091565b60006001600160e01b03198216635a05180f60e01b1480610a795750610a7982612c14565b92915050565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace038054606091600080516020615d5c83398151915291610abe906153b7565b80601f0160208091040260200160405190810160405280929190818152602001828054610aea906153b7565b8015610b375780601f10610b0c57610100808354040283529160200191610b37565b820191906000526020600020905b815481529060010190602001808311610b1a57829003601f168201915b505050505091505090565b6000610b4c612aa2565b600a5460ff1615610b705760405163539409e360e11b815260040160405180910390fd5b610b78612c49565b601b54421015610b9b576040516346f80f1f60e01b815260040160405180910390fd5b6000610ba76002612c7c565b80519091506000805b82811015610c135760156001016000858381518110610bd157610bd16153eb565b6020908102919091018101516001600160a01b031682528101919091526040016000205460ff1615610c0b5781610c0781615417565b9250505b600101610bb0565b506000816001600160401b03811115610c2e57610c2e615430565b604051908082528060200260200182016040528015610c57578160200160208202803683370190505b5090506000826001600160401b03811115610c7457610c74615430565b604051908082528060200260200182016040528015610cc957816020015b610cb660405180606001604052806000815260200160008152602001600081525090565b815260200190600190039081610c925790505b5090506000836001600160401b03811115610ce657610ce6615430565b604051908082528060200260200182016040528015610d2b57816020015b6040805180820190915260008082526020820152815260200190600190039081610d045790505b5090506000935060005b85811015610e6157600060156001016000898481518110610d5857610d586153eb565b6020908102919091018101516001600160a01b03168252810191909152604001600020805490915060ff1615610e5857878281518110610d9a57610d9a6153eb565b6020026020010151858781518110610db457610db46153eb565b6001600160a01b03909216602092830291909101820152604080516060810182526002840154808252928101839052908101919091528451859088908110610dfe57610dfe6153eb565b60200260200101819052508060040160405180604001604052908160008201548152602001600182015481525050838781518110610e3e57610e3e6153eb565b60200260200101819052508580610e5490615417565b9650505b50600101610d35565b50604080516060810182526018548082526020820181905291810191909152610e8f89858585856078612c89565b975050505050505050610ea0612aec565b919050565b600033610eb3818585612e2f565b5060019392505050565b6000806000610eca612e3c565b50915091508082610ef97f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace025490565b610f039190615446565b610f0d9190615446565b9250505090565b610f1c612aa2565b610f24612c49565b610a27612aec565b6000610f3781612b12565b610f4183836131f0565b505050565b7f4ff6ae4d6a29e79ca45c6441bdc89b93878ac6118485b33c8baa3749fc3cb130610f7081612b12565b610f78612aa2565b600a5460ff1615610f9c5760405163539409e360e11b815260040160405180910390fd5b610fa4612c49565b73caf303d82520bec16a1615538212985787c9a02a6394c99206610fc86002612c7c565b6020546040516001600160e01b031960e085901b16815261100292916014916015918d918d918d918d918d9160ff90911690600401615459565b60006040518083038186803b15801561101a57600080fd5b505af415801561102e573d6000803e3d6000fd5b5050505060005b858110156110775761106e878783818110611052576110526153eb565b611069926020610100909202019081019150614cf2565b6132d0565b50600101611035565b50611080612aec565b505050505050565b611090612aa2565b61109b60003361219a565b806110cb57506110cb7f4ff6ae4d6a29e79ca45c6441bdc89b93878ac6118485b33c8baa3749fc3cb1303361219a565b806110fb57506110fb7f13ff1b2625181b311f257c723b5e6d366eb318b212d9dd694c48fcf227659df53361219a565b61111857604051637bdeee5360e11b815260040160405180910390fd5b6000818152601e602052604090206003015442116111795761113b60014261555f565b6000828152601e602052604080822060030192909255905182917fac4a907ec29adcc56774b757ecb1e1b4d597374fc9386107d05e2670259df7d391a25b611181612aec565b50565b60003361119285828561334f565b61119d8585856133af565b60019150505b9392505050565b6000908152600080516020615d7c833981519152602052604090206001015490565b6111d5826111aa565b6111de81612b12565b6111e8838361340e565b50505050565b60006111f8612aa2565b600a5460ff161561121c5760405163539409e360e11b815260040160405180910390fd5b611224612c49565b6012546001600160a01b0316158015906112475750601254600160a01b900460ff165b611264576040516387db439760e01b815260040160405180910390fd5b6000868152601e6020526040812081906112849088888460001980613453565b5091509150806000036112aa57604051630ad5378760e01b815260040160405180910390fd5b6012546040516333f363a360e01b81523360048201526001600160a01b03878116602483015260448201879052909116906333f363a3906064016020604051808303816000875af1158015611303573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113279190615572565b9250611334878484613581565b6040516314d6c7d760e31b81523060048201526001600160a01b0388811660248301528781166044830152606482018490526084820183905284169063a6b63eb89060a401600060405180830381600087803b15801561139357600080fd5b505af11580156113a7573d6000803e3d6000fd5b5050601380546001600160a01b0319166001600160a01b0387169081179091556040519081528a92507f7e8e2491200fd9e2cf2541c7229d5bf89f4da14659c18fc31054176c339e310b915060200160405180910390a25050611408612aec565b95945050505050565b6001600160a01b038116331461143a5760405163334bd91960e11b815260040160405180910390fd5b610f41828261363f565b61144c612aa2565b600061145781612b12565b611460826132d0565b61147d5760405163420aca6760e01b815260040160405180910390fd5b50611181612aec565b60018054611493906153b7565b80601f01602080910402602001604051908101604052809291908181526020018280546114bf906153b7565b801561150c5780601f106114e15761010080835404028352916020019161150c565b820191906000526020600020905b8154815290600101906020018083116114ef57829003601f168201915b505050505081565b60007f13ff1b2625181b311f257c723b5e6d366eb318b212d9dd694c48fcf227659df561154081612b12565b611548612aa2565b600a5460ff161561156c5760405163539409e360e11b815260040160405180910390fd5b611574612c49565b8760005b818110156115ed57601660008c8c84818110611596576115966153eb565b90506020020160208101906115ab9190614cf2565b6001600160a01b0316815260208101919091526040016000205460ff166115e55760405163445e1f2b60e11b815260040160405180910390fd5b600101611578565b506116f18b8b8b80806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f820116905080830192505050505050508a8a808060200260200160405190810160405280939291908181526020016000905b8282101561168257611673606083028601368190038101906155e7565b81526020019060010190611656565b50505050508989808060200260200160405190810160405280939291908181526020016000905b828210156116d5576116c660408302860136819003810190615603565b815260200190600101906116a9565b506116ea9350505050368a90038a018a6155e7565b6000612c89565b92506117326015600601546078601e600f544261170e9190615446565b6117189190615446565b6117229190615446565b61172d906001615446565b61367b565b601b555061173e612aec565b5098975050505050505050565b6000806117797f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005460021490565b6013549092506001600160a01b0316158015906118085750601360009054906101000a90046001600160a01b03166001600160a01b031663d6dacb446040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118089190615653565b90509091565b6004818154811061181e57600080fd5b6000918252602090912001546001600160a01b0381169150600160a01b90046001600160601b031682565b60408051808201825260008082526020918201819052848152601e82528281206001600160a01b038516825260019081018352838220845180860190955280548086529101549284019290925203610a795760405163445e1f2b60e11b815260040160405180910390fd5b6000848152601e60205260408120819081906118d69087878488600019613453565b9250925092509450945094915050565b6118ee612aa2565b60006118f981612b12565b600a805460ff191660011790556040517f0896631e72e873e636ab9ad7599a61ddc2f96c7961fa8e19e00a926e6512312390600090a150610a27612aec565b6000806000611945612e3c565b509092509050610f0d8183615446565b606080611960612aa2565b600a5460ff16156119845760405163539409e360e11b815260040160405180910390fd5b61198c612c49565b600080546040516311a04fa160e11b8152306004820152829182916001600160a01b03909116906323409f4290602401608060405180830381865afa1580156119d9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119fd9190615670565b93509350935050611a1581660110d9316ec00061367b565b90506000670de0b6b3a76400006001670de0b6b3a76400006006548c611a3b91906156af565b611a459190615446565b611a4f919061555f565b611a5991906156dc565b9050600083600181611a6b88866156af565b611a759190615446565b611a7f919061555f565b611a8991906156dc565b90506000670de0b6b3a7640000600181611aa3878f6156af565b611aad9190615446565b611ab7919061555f565b611ac191906156dc565b9050808210611ad05781611ad2565b805b9150818310611ae15782611ae3565b815b92506000611af1848d61555f565b90508015801590611b025750898110155b611b1f57604051632cf5f58f60e21b815260040160405180910390fd5b611b2a8c600161368b565b8151919a50985060005b81811015611ba357898181518110611b4e57611b4e6153eb565b6020026020010151600014611b9b57611b9b8b8281518110611b7257611b726153eb565b602002602001015133308d8581518110611b8e57611b8e6153eb565b6020026020010151613708565b600101611b34565b50611bae8c83613741565b8360086000828254611bc09190615446565b90915550611bd09050848661555f565b60096000828254611be19190615446565b925050819055505050505050505050611bf8612aec565b935093915050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff1615906001600160401b0316600081158015611c455750825b90506000826001600160401b03166001148015611c615750303b155b905081158015611c6f575080155b15611c8d5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315611cb757845460ff60401b1916600160401b1785555b611d40611cc48b806156f0565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611d069250505060208d018d6156f0565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061377792505050565b611d48613789565b611d50613789565b611d58613791565b611d6d611d6860208b018b615736565b6137a1565b611d7a89604001356139ea565b611d878960600135613b23565b611d918935613b80565b611da6611da160808b018b6156f0565b613be6565b611db287602001612b1c565b611dca611dc56080890160608a01614fef565b613c25565b611def611ddd60408a0160208b01614cf2565b611dea60208a018a614fef565b6131f0565b611e04611dff60208a018a614cf2565b613c63565b8960800135600003611e2957604051631f6d979160e11b815260040160405180910390fd5b6000611e3860408c018c61577f565b9050905080600003611e5d5760405163e9eaf68960e01b815260040160405180910390fd5b60005b81811015612007576000611e7760408e018e61577f565b83818110611e8757611e876153eb565b9050602002016020810190611e9c9190614cf2565b6001600160a01b031603611ec35760405163445e1f2b60e11b815260040160405180910390fd5b6000611ed260408e018e61577f565b83818110611ee257611ee26153eb565b9050602002016020810190611ef79190614cf2565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015611f3d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f6191906157c8565b9050801515611f7360408f018f61577f565b84818110611f8357611f836153eb565b9050602002016020810190611f989190614cf2565b90611fc757604051631b58637360e21b81526001600160a01b0390911660048201526024015b60405180910390fd5b50611ffd611fd860408f018f61577f565b84818110611fe857611fe86153eb565b90506020020160208101906110699190614cf2565b5050600101611e60565b504260075561201a8760808d0135613741565b61202560003361340e565b5050831561206d57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050505050565b612081612aa2565b612089613cac565b61209460003361219a565b8061212857506001600160a01b03811660009081526016602052604090206002015415801561212857506040516370a0823160e01b81523060048201526001600160a01b038216906370a0823190602401602060405180830381865afa158015612102573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061212691906157c8565b155b6121455760405163019b497f60e51b815260040160405180910390fd5b61214e81613d6f565b6111795760405163420aca6760e01b815260040160405180910390fd5b6000828152600080516020615d3c8339815191526020819052604082206121929084613dfc565b949350505050565b6000918252600080516020615d7c833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace048054606091600080516020615d5c83398151915291610abe906153b7565b600061221c81612b12565b610a3d82613c25565b600061223081612b12565b610f418383613be6565b600061224581612b12565b61224d612672565b610a3d826139ea565b6000818152600080516020615d3c83398151915260208190526040909120606091906111a390612c7c565b600033610eb38185856133af565b60008060606122b860405180606001604052806000815260200160008152602001600081525090565b6122dc60405180606001604052806000815260200160008152602001600081525090565b601554601d5490955060ff1693506000806122f76002612c7c565b8051909150806001600160401b0381111561231457612314615430565b60405190808252806020026020018201604052801561234d57816020015b61233a614929565b8152602001906001900390816123325790505b50955060005b8181101561242b57600083828151811061236f5761236f6153eb565b6020908102919091018101516001600160a01b038116600081815260168452604090819020815160a0810183529283528151606080820184526001830154825260028301548288015260038301548285015284870191909152825180840184526004830154815260058301549681019690965291830194909452600684015490820152825460ff16151560808201528a51919350908a9085908110612416576124166153eb565b60209081029190910101525050600101612353565b5050604080516060808201835260175482526018546020808401919091526019548385015283519182018452601a548252601b5490820152601c5492810192909252601d54989997989697909691955061010090910460ff169350915050565b6060612495612aa2565b61249d612c49565b60606124aa88600061368b565b925090506124b83389613e08565b805185811480156124c857508084145b6124e557604051635feae2b760e01b815260040160405180910390fd5b60005b8181101561264157878782818110612502576125026153eb565b90506020020160208101906125179190614cf2565b6001600160a01b0316838281518110612532576125326153eb565b60200260200101516001600160a01b0316146125615760405163445e1f2b60e11b815260040160405180910390fd5b858582818110612573576125736153eb565b9050602002013584828151811061258c5761258c6153eb565b602002602001015110158382815181106125a8576125a86153eb565b6020026020010151906125da57604051631b58637360e21b81526001600160a01b039091166004820152602401611fbe565b508381815181106125ed576125ed6153eb565b602002602001015160001461263957612639838281518110612611576126116153eb565b60200260200101518a86848151811061262c5761262c6153eb565b6020026020010151613e3e565b6001016124e8565b50505061264c612aec565b9695505050505050565b61265e612aa2565b600061266981612b12565b61147d82613b80565b61267a612aa2565b612682612c49565b60098054600091829055600454909190815b8181101561278f576000670de0b6b3a7640000600483815481106126ba576126ba6153eb565b6000918252602090912001546126e090600160a01b90046001600160601b0316876156af565b6126ea91906156dc565b90506126f68185615446565b93506127296004838154811061270e5761270e6153eb565b6000918252602090912001546001600160a01b031682613741565b6004828154811061273c5761273c6153eb565b600091825260209182902001546040518381526001600160a01b03909116917f168a65529db3a11aa555b702a0e4594e364bfeebed05918eeb405d36e744fa51910160405180910390a250600101612694565b50600082846008546127a19190615446565b6127ab919061555f565b600080546040516311a04fa160e11b815230600482015292935090916001600160a01b03909116906323409f4290602401608060405180830381865afa1580156127f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061281d9190615670565b505050905061282c8183613741565b806001600160a01b03167fb87e607f6030a23ed9b7dac1a717610f3a3b07325269f18808ba763bdcefe7ae8360405161286791815260200190565b60405180910390a25050600060085550610a279150612aec9050565b600061288e81612b12565b610f418383613e6f565b6000818152600080516020615d3c8339815191526020819052604082206111a390613ee9565b60006128c8612aa2565b600a5460ff16156128ec5760405163539409e360e11b815260040160405180910390fd5b6128f4612c49565b601d54610100900460ff1661291c5760405163dd4cec2560e01b815260040160405180910390fd5b6000898152601e60205260409020612938818a8a8a808b613453565b50604051635f4fc08760e11b815290935073caf303d82520bec16a1615538212985787c9a02a915063be9f810e906129849084908e908e908e908e908a908e908e908e9060040161580a565b602060405180830381865af41580156129a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129c59190615653565b156129d5576129d389613d6f565b505b506129de612aec565b98975050505050505050565b6060806129f7848461368b565b915091505b9250929050565b612a0c826111aa565b612a1581612b12565b6111e8838361363f565b6001600160a01b0391821660009081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020908152604080832093909416825291909152205490565b6000612a7481612b12565b612a7c612672565b610f4183836137a1565b6000612a9181612b12565b612a99612672565b610a3d82613b23565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00805460011901612ae657604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b6111818133613ef3565b806014612b298282615877565b9050507f0aab3571baa3ce57a744138e4bb529992ae0398bbfc12b2ae79ecf1cc94ec25a81604051612b5b91906158da565b60405180910390a150565b606080612b736002612c7c565b8051909250806001600160401b03811115612b9057612b90615430565b604051908082528060200260200182016040528015612bb9578160200160208202803683370190505b50915060005b81811015612c0e57612be9848281518110612bdc57612bdc6153eb565b6020026020010151613f2c565b838281518110612bfb57612bfb6153eb565b6020908102919091010152600101612bbf565b50509091565b60006001600160e01b03198216637965db0b60e01b1480610a7957506301ffc9a760e01b6001600160e01b0319831614610a79565b612c51613cac565b6000806000612c5e612e3c565b925092509250600754811115610f4157600892909255600955600755565b606060006111a383614125565b60155460009087148015612caa5750601a54612ca6908390615446565b4210155b8015612cb75750601c5442105b612cd45760405163089b3fa160e31b815260040160405180910390fd5b601f54600003612ce657600b54612cea565b601f545b9050612cf7816001615446565b601f558015612dad576000601e81612d1060018561555f565b81526020019081526020016000209050878160000154148015612d42575042838260030154612d3f9190615446565b10155b15612dab578215612d66576040516346f80f1f60e01b815260040160405180910390fd5b612d7160014261555f565b6003820155612d8160018361555f565b6040517fac4a907ec29adcc56774b757ecb1e1b4d597374fc9386107d05e2670259df7d390600090a25b505b600f5460405163fba540c760e01b815273caf303d82520bec16a1615538212985787c9a02a9163fba540c791612df591601591601e9187918d918d918d918d9160040161594f565b60006040518083038186803b158015612e0d57600080fd5b505af4158015612e21573d6000803e3d6000fd5b505050509695505050505050565b610f418383836001614181565b6000808062015180612e4e81426156dc565b612e5891906156af565b905060006007548211612e6c576000612e79565b600754612e79908361555f565b905080600003612e985760085460095460075493509350935050909192565b6008549350600954925060008385612ece7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace025490565b612ed89190615446565b612ee29190615446565b600080546040516311a04fa160e11b81523060048201529293509091829182916001600160a01b03909116906323409f4290602401608060405180830381865afa158015612f34573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f589190615670565b935093509350506000731d84718cf856c82e71499ec02c8b52a392b8fce3632e4c697f83670de0b6b3a7640000612f8f919061555f565b6040516001600160e01b031960e084901b16815260048101919091526407620d06ef6024820152604401602060405180830381865af4158015612fd6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ffa91906157c8565b61300c90670de0b6b3a764000061555f565b90506000600554821161302157600554613023565b815b9050600086731d84718cf856c82e71499ec02c8b52a392b8fce36399a04f2f61305485670de0b6b3a764000061555f565b8b6040518363ffffffff1660e01b815260040161307b929190918252602082015260400190565b602060405180830381865af4158015613098573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130bc91906157c8565b6130ce670de0b6b3a76400008a6156af565b6130d891906156dc565b6130e2919061555f565b90506000826001816130fc670de0b6b3a7640000886156af565b6131069190615446565b613110919061555f565b61311a91906156dc565b9050600086600181613134670de0b6b3a76400008c6156af565b61313e9190615446565b613148919061555f565b61315291906156dc565b821161318957866001816131668b876156af565b6131709190615446565b61317a919061555f565b61318491906156dc565b6131bd565b670de0b6b3a764000060018161319f85876156af565b6131a99190615446565b6131b3919061555f565b6131bd91906156dc565b90506131c9818e615446565b9c506131d5818461555f565b6131df908d615446565b9b5050505050505050505050909192565b6012546001600160a01b0383811691161461324b576012546001600160a01b03161561322f576040516312794cc760e21b815260040160405180910390fd5b601280546001600160a01b0319166001600160a01b0384161790555b60125460ff600160a01b9091041615158115151461327b576012805460ff60a01b1916600160a01b831515021790555b601254604080516001600160a01b0383168152600160a01b90920460ff16151560208301527f5806f7ef7f8d6bafce97caf329ff62db253b61c867a1b2c4da9e79dbc4ec2f2291015b60405180910390a15050565b60006001600160a01b038216158015906132f357506001600160a01b0382163014155b6133105760405163445e1f2b60e11b815260040160405180910390fd5b6040516001600160a01b038316907f59b7c8b22741836fc393dc21baa2e8157e039b28c3ee59310f38b2847a2dd29c90600090a2610a79600283614268565b600061335b8484612a1f565b905060001981146111e857818110156133a057604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401611fbe565b6111e884848484036000614181565b6001600160a01b0383166133d957604051634b637e8f60e11b815260006004820152602401611fbe565b6001600160a01b0382166134035760405163ec442f0560e01b815260006004820152602401611fbe565b610f4183838361427d565b6000600080516020615d3c8339815191528161342a85856142b1565b9050801561219257600085815260208390526040902061344a9085614268565b50949350505050565b6000806000806040518060c0016040528061346c610ebd565b815260200161347a8b613f2c565b81526020016134888a613f2c565b815260208082018a905260408083018a90526060928301899052805163ef27b38b60e01b815260156004820152602481018f90526001600160a01b03808f1660448301528d166064820152845160848201529184015160a483015283015160c48201529082015160e4820152608082015161010482015260a082015161012482015290915073caf303d82520bec16a1615538212985787c9a02a9063ef27b38b9061014401606060405180830381865af415801561354a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061356e9190615a19565b919c909b50909950975050505050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526135d2848261435d565b6111e8576040516001600160a01b0384811660248301526000604483015261363591869182169063095ea7b3906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b0383818316178352505050506143a7565b6111e884826143a7565b6000600080516020615d3c8339815191528161365b8585614418565b9050801561219257600085815260208390526040902061344a9085614494565b60008282188284110282186111a3565b6060806000613698610ebd565b90506136a2612b66565b8151919450925060005b818110156136fe576136d9878583815181106136ca576136ca6153eb565b602002602001015185896144a9565b8482815181106136eb576136eb6153eb565b60209081029190910101526001016136ac565b5050509250929050565b6040516001600160a01b0384811660248301528381166044830152606482018390526111e89186918216906323b872dd90608401613603565b6001600160a01b03821661376b5760405163ec442f0560e01b815260006004820152602401611fbe565b610a3d6000838361427d565b61377f6144ed565b610a3d8282614536565b610a276144ed565b6137996144ed565b610a27614587565b7fb8dde4be9101cab9d9d994925b7817605b5ce5834e63618484b8b4e5bef6a54882826040516137d2929190615a5c565b60405180910390a160045460005b818110156138195760048054806137f9576137f9615ac5565b6000828152602081208201600019908101919091550190556001016137e0565b50819050600081900361382b57505050565b604081111561384d57604051636516935760e11b815260040160405180910390fd5b60008060005b838110156139ba57826001600160a01b0316868683818110613877576138776153eb565b61388d9260206040909202019081019150614cf2565b6001600160a01b0316116138b4576040516341dc215f60e11b815260040160405180910390fd5b8585828181106138c6576138c66153eb565b90506040020160200160208101906138de9190615adb565b6001600160601b03166000036139075760405163011becf960e01b815260040160405180910390fd5b858582818110613919576139196153eb565b90506040020160200160208101906139319190615adb565b613944906001600160601b031683615446565b9150858582818110613958576139586153eb565b61396e9260206040909202019081019150614cf2565b92506004868683818110613984576139846153eb565b835460018101855560009485526020909420604090910292909201929190910190506139b08282615af8565b5050600101613853565b50670de0b6b3a764000081146139e35760405163f79b6e4960e01b815260040160405180910390fd5b5050505050565b67016345785d8a0000811115613a13576040516302aec4d160e11b815260040160405180910390fd5b731d84718cf856c82e71499ec02c8b52a392b8fce3632e4c697f613a3f83670de0b6b3a764000061555f565b6040516001600160e01b031960e084901b16815260048101919091526407620d06ef6024820152604401602060405180830381865af4158015613a86573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613aaa91906157c8565b613abc90670de0b6b3a764000061555f565b600555801580613acd575060055415155b613aea57604051637c379aa760e11b815260040160405180910390fd5b60055460408051918252602082018390527f504285076b3e8a5b35bb309459af128be9f7cf48f7aab9e599332a1e79cb541e9101612b5b565b66b1a2bc2ec50000811115613b4b5760405163330e445d60e01b815260040160405180910390fd5b60068190556040518181527f97aee230ba41961438e908e115df76fa8113f85a0586d85b19ba5be50e6a227490602001612b5b565b603c8110158015613b94575062093a808111155b613bb15760405163bb80f28f60e01b815260040160405180910390fd5b600f8190556040518181527f99578d7fe3e20e279feceaa076eb8032d475ca1a49391ec0a740445152a5971390602001612b5b565b6001613bf3828483615b88565b507f7332b59e42a46838955f2abeac0a553dd3870441c46bbfb13728d9b2cc5fb6d482826040516132c4929190615c47565b6020805460ff191682151590811782556040519081527f3a36c64f4c802a228a73bcefb9f4649599935095775ea1da27c6265db9f4f5569101612b5b565b6001600160a01b038116613c8a57604051635908381f60e11b815260040160405180910390fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6013546001600160a01b031615610a275773caf303d82520bec16a1615538212985787c9a02a6358c4ab4e601e60006001601f54613cea919061555f565b815260208101919091526040908101600020601354915160e084901b6001600160e01b031916815260048101919091526001600160a01b03909116602482015260440160006040518083038186803b158015613d4557600080fd5b505af4158015613d59573d6000803e3d6000fd5b5050601380546001600160a01b03191690555050565b6040516000906001600160a01b038316907f4e3a022fa7a66b1e055fe6b819a1afe69dc1d44c43de4af7b32f095e603884ae908390a26001600160a01b0382166000908152601660205260408120805460ff19168155600181018290556002808201839055600382018390556004820183905560058201839055600690910191909155610a799083614494565b60006111a3838361458f565b6001600160a01b038216613e3257604051634b637e8f60e11b815260006004820152602401611fbe565b610a3d8260008361427d565b6040516001600160a01b03838116602483015260448201839052610f4191859182169063a9059cbb90606401613603565b600080516020615d5c8339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace03613eaa838583615b88565b507f13c98778b0c1a086bb98d7f1986e15788b5d3a1ad4c492e1d78f1c4cc51c20cf8383604051613edc929190615c47565b60405180910390a1505050565b6000610a79825490565b613efd828261219a565b610a3d5760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401611fbe565b6040516370a0823160e01b81523060048201526000906001600160a01b038316906370a0823190602401602060405180830381865afa158015613f73573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f9791906157c8565b6013549091506001600160a01b0316158015906140a85750601354604080516309769f0b60e41b815290516001600160a01b03808616931691639769f0b09160048083019260209291908290030181865afa158015613ffa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061401e9190615572565b6001600160a01b031614806140a857506013546040805163a482171960e01b815290516001600160a01b0380861693169163a48217199160048083019260209291908290030181865afa158015614079573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061409d9190615572565b6001600160a01b0316145b15610ea0576013546040516370a0823160e01b81526001600160a01b039182166004820152908316906370a0823190602401602060405180830381865afa1580156140f7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061411b91906157c8565b610a799082615446565b60608160000180548060200260200160405190810160405280929190818152602001828054801561417557602002820191906000526020600020905b815481526020019060010190808311614161575b50505050509050919050565b600080516020615d5c8339815191526001600160a01b0385166141ba5760405163e602df0560e01b815260006004820152602401611fbe565b6001600160a01b0384166141e457604051634a1406b160e11b815260006004820152602401611fbe565b6001600160a01b038086166000908152600183016020908152604080832093881683529290522083905581156139e357836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258560405161425991815260200190565b60405180910390a35050505050565b60006111a3836001600160a01b0384166145b9565b306001600160a01b038316036142a657604051631df47fd760e11b815260040160405180910390fd5b610f41838383614608565b6000600080516020615d7c8339815191526142cc848461219a565b61434c576000848152602082815260408083206001600160a01b03871684529091529020805460ff191660011790556143023390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a46001915050610a79565b6000915050610a79565b5092915050565b6000806000806020600086516020880160008a5af192503d9150600051905082801561264c57508115614393578060011461264c565b50505050506001600160a01b03163b151590565b600080602060008451602086016000885af1806143ca576040513d6000823e3d81fd5b50506000513d915081156143e25780600114156143ef565b6001600160a01b0384163b155b156111e857604051635274afe760e01b81526001600160a01b0385166004820152602401611fbe565b6000600080516020615d7c833981519152614433848461219a565b1561434c576000848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a46001915050610a79565b60006111a3836001600160a01b038416614746565b60006144d86144b78361482f565b80156144d35750600084806144ce576144ce6156c6565b868809115b151590565b6144e386868661485c565b6114089190615446565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16610a2757604051631afcd79f60e31b815260040160405180910390fd5b61453e6144ed565b600080516020615d5c8339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace036145788482615c5b565b50600481016111e88382615c5b565b612aec6144ed565b60008260000182815481106145a6576145a66153eb565b9060005260206000200154905092915050565b600081815260018301602052604081205461460057508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610a79565b506000610a79565b600080516020615d5c8339815191526001600160a01b03841661464457818160020160008282546146399190615446565b909155506146b69050565b6001600160a01b038416600090815260208290526040902054828110156146975760405163391434e360e21b81526001600160a01b03861660048201526024810182905260448101849052606401611fbe565b6001600160a01b03851660009081526020839052604090209083900390555b6001600160a01b0383166146d45760028101805483900390556146f3565b6001600160a01b03831660009081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161473891815260200190565b60405180910390a350505050565b6000818152600183016020526040812054801561434c57600061476a60018361555f565b855490915060009061477e9060019061555f565b90508082146147e357600086600001828154811061479e5761479e6153eb565b90600052602060002001549050808760000184815481106147c1576147c16153eb565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806147f4576147f4615ac5565b600190038181906000526020600020016000905590558560010160008681526020019081526020016000206000905560019350505050610a79565b60006002826003811115614845576148456150a1565b61484f9190615d19565b60ff166001149050919050565b600083830281600019858709828110838203039150508060000361489357838281614889576148896156c6565b04925050506111a3565b8084116148aa576148aa6003851502601118614917565b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b634e487b71600052806020526024601cfd5b6040518060a0016040528060006001600160a01b0316815260200161496860405180606001604052806000815260200160008152602001600081525090565b815260200161498a604051806040016040528060008152602001600081525090565b815260006020820181905260409091015290565b6000604082840312156149b057600080fd5b50919050565b6000604082840312156149c857600080fd5b6111a3838361499e565b600081518084526020840193506020830160005b82811015614a0d5781516001600160a01b03168652602095860195909101906001016149e6565b5093949350505050565b600081518084526020840193506020830160005b82811015614a0d578151865260209586019590910190600101614a2b565b604081526000614a5c60408301856149d2565b82810360208401526114088185614a17565b600060208284031215614a8057600080fd5b81356001600160e01b0319811681146111a357600080fd5b602081526000825180602084015260005b81811015614ac65760208186018101516040868401015201614aa9565b506000604082850101526040601f19601f83011684010191505092915050565b600060208284031215614af857600080fd5b5035919050565b6001600160a01b038116811461118157600080fd5b60008060408385031215614b2757600080fd5b8235614b3281614aff565b946020939093013593505050565b801515811461118157600080fd5b60008060408385031215614b6157600080fd5b8235614b6c81614aff565b91506020830135614b7c81614b40565b809150509250929050565b6000606082840312156149b057600080fd5b600080600080600060c08688031215614bb157600080fd5b85356001600160401b03811115614bc757600080fd5b8601601f81018813614bd857600080fd5b80356001600160401b03811115614bee57600080fd5b8860208260081b8401011115614c0357600080fd5b602091820196509450614c199088908801614b87565b949793965093946080810135945060a0013592915050565b600080600060608486031215614c4657600080fd5b8335614c5181614aff565b92506020840135614c6181614aff565b929592945050506040919091013590565b60008060408385031215614c8557600080fd5b823591506020830135614b7c81614aff565b600080600080600060a08688031215614caf57600080fd5b853594506020860135614cc181614aff565b93506040860135614cd181614aff565b92506060860135614ce181614aff565b949793965091946080013592915050565b600060208284031215614d0457600080fd5b81356111a381614aff565b60008083601f840112614d2157600080fd5b5081356001600160401b03811115614d3857600080fd5b6020830191508360208260051b85010111156129fc57600080fd5b60008083601f840112614d6557600080fd5b5081356001600160401b03811115614d7c57600080fd5b6020830191508360208260061b85010111156129fc57600080fd5b60008060008060008060008060e0898b031215614db357600080fd5b8835975060208901356001600160401b03811115614dd057600080fd5b614ddc8b828c01614d0f565b90985096505060408901356001600160401b03811115614dfb57600080fd5b8901601f81018b13614e0c57600080fd5b80356001600160401b03811115614e2257600080fd5b8b6020606083028401011115614e3757600080fd5b6020919091019550935060608901356001600160401b03811115614e5a57600080fd5b614e668b828c01614d53565b9094509250614e7a90508a60808b01614b87565b90509295985092959890939650565b815181526020808301519082015260408101610a79565b60008060008060808587031215614eb657600080fd5b843593506020850135614ec881614aff565b92506040850135614ed881614aff565b9396929550929360600135925050565b600080600060608486031215614efd57600080fd5b833592506020840135614c6181614aff565b600060a082840312156149b057600080fd5b6000806000806000858703610120811215614f3b57600080fd5b86356001600160401b03811115614f5157600080fd5b614f5d89828a01614f0f565b96505060208701356001600160401b03811115614f7957600080fd5b614f8589828a01614f0f565b955050614f95886040890161499e565b93506080607f1982011215614fa957600080fd5b50608086019150610100860135614fbf81614aff565b809150509295509295909350565b60008060408385031215614fe057600080fd5b50508035926020909101359150565b60006020828403121561500157600080fd5b81356111a381614b40565b60008083601f84011261501e57600080fd5b5081356001600160401b0381111561503557600080fd5b6020830191508360208285010111156129fc57600080fd5b6000806020838503121561506057600080fd5b82356001600160401b0381111561507657600080fd5b6150828582860161500c565b90969095509350505050565b6020815260006111a360208301846149d2565b634e487b7160e01b600052602160045260246000fd5b600381106150d557634e487b7160e01b600052602160045260246000fd5b9052565b600061014082018883526150f060208401896150b7565b6101406040840152865190819052602087019061016084019060005b8181101561518757835180516001600160a01b0316845260208082015180518287015290810151604080870191909152810151606086015250604081015180516080860152602081015160a086015250606081015160c085015260800151151560e0840152602093909301926101009092019160010161510c565b50508651606085015260208701516080850152604087015160a085015291506151ad9050565b835160c0830152602084015160e083015260409093015161010082015290151561012090910152949350505050565b600080600080600080608087890312156151f557600080fd5b86359550602087013561520781614aff565b945060408701356001600160401b0381111561522257600080fd5b61522e89828a01614d0f565b90955093505060608701356001600160401b0381111561524d57600080fd5b61525989828a01614d0f565b979a9699509497509295939492505050565b6020815260006111a36020830184614a17565b60008060008060008060008060e0898b03121561529a57600080fd5b8835975060208901356152ac81614aff565b965060408901356152bc81614aff565b9550606089013594506080890135935060a08901356152da81614b40565b925060c08901356001600160401b038111156152f557600080fd5b6153018b828c0161500c565b999c989b5096995094979396929594505050565b6000806040838503121561532857600080fd5b82359150602083013560048110614b7c57600080fd5b8215158152604081016111a360208301846150b7565b6000806040838503121561536757600080fd5b823561537281614aff565b91506020830135614b7c81614aff565b6000806020838503121561539557600080fd5b82356001600160401b038111156153ab57600080fd5b61508285828601614d53565b600181811c908216806153cb57607f821691505b6020821081036149b057634e487b7160e01b600052602260045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60006001820161542957615429615401565b5060010190565b634e487b7160e01b600052604160045260246000fd5b80820180821115610a7957610a79615401565b6101408152600061546e61014083018c6149d2565b60208381018c9052604084018b9052838203606085015288825289910160005b898110156155105782356154a181614aff565b6001600160a01b031682526020838101359083015260408084013590830152606080840135908301526080838101359083015260a0808401359083015260c0808401359083015260e08301356154f681614b40565b151560e0830152610100928301929091019060010161548e565b5087356080850152602088013560a0850152604088013560c085015291506155359050565b8460e08301528361010083015261555161012083018415159052565b9a9950505050505050505050565b81810381811115610a7957610a79615401565b60006020828403121561558457600080fd5b81516111a381614aff565b6000606082840312156155a157600080fd5b604051606081016001600160401b03811182821017156155c3576155c3615430565b60409081528335825260208085013590830152928301359281019290925250919050565b6000606082840312156155f957600080fd5b6111a3838361558f565b6000604082840312801561561657600080fd5b50604080519081016001600160401b038111828210171561563957615639615430565b604052823581526020928301359281019290925250919050565b60006020828403121561566557600080fd5b81516111a381614b40565b6000806000806080858703121561568657600080fd5b845161569181614aff565b60208601516040870151606090970151919890975090945092505050565b8082028115828204841417610a7957610a79615401565b634e487b7160e01b600052601260045260246000fd5b6000826156eb576156eb6156c6565b500490565b6000808335601e1984360301811261570757600080fd5b8301803591506001600160401b0382111561572157600080fd5b6020019150368190038213156129fc57600080fd5b6000808335601e1984360301811261574d57600080fd5b8301803591506001600160401b0382111561576757600080fd5b6020019150600681901b36038213156129fc57600080fd5b6000808335601e1984360301811261579657600080fd5b8301803591506001600160401b038211156157b057600080fd5b6020019150600581901b36038213156129fc57600080fd5b6000602082840312156157da57600080fd5b5051919050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b898152602081018990526001600160a01b038881166040830152871660608201526080810186905260a0810185905283151560c082015261010060e0820181905260009061585b90830184866157e1565b9b9a5050505050505050505050565b6003811061118157600080fd5b813561588281614b40565b815460ff19811691151560ff16918217835560208401356158a28161586a565b600381106158c057634e487b7160e01b600052602160045260246000fd5b61ff008160081b168361ffff198416171784555050505050565b6040810182356158e981614b40565b1515825260208301356158fb8161586a565b61435660208401826150b7565b600081518084526020840193506020830160005b82811015614a0d5761593986835180518252602090810151910152565b604095909501946020919091019060010161591c565b888152876020820152866040820152610140606082015260006159766101408301886149d2565b82810360808401528651808252602080890192019060005b818110156159cb576159b58385518051825260208082015190830152604090810151910152565b602093909301926060929092019160010161598e565b505083810360a08501526159df8188615908565b865160c0860152602087015160e086015260408701516101008601529250615a05915050565b826101208301529998505050505050505050565b600080600060608486031215615a2e57600080fd5b5050815160208301516040909301519094929350919050565b6001600160601b038116811461118157600080fd5b6020808252810182905260008360408301825b85811015615abb578235615a8281614aff565b6001600160a01b031682526020830135615a9b81615a47565b6001600160601b0316602083015260409283019290910190600101615a6f565b5095945050505050565b634e487b7160e01b600052603160045260246000fd5b600060208284031215615aed57600080fd5b81356111a381615a47565b8135615b0381614aff565b81546001600160a01b0319166001600160a01b039190911690811782556020830135615b2e81615a47565b60a01b6001600160a01b03191617905550565b601f821115610f4157806000526020600020601f840160051c81016020851015615b685750805b601f840160051c820191505b818110156139e35760008155600101615b74565b6001600160401b03831115615b9f57615b9f615430565b615bb383615bad83546153b7565b83615b41565b6000601f841160018114615be75760008515615bcf5750838201355b600019600387901b1c1916600186901b1783556139e3565b600083815260209020601f19861690835b82811015615c185786850135825560209485019460019092019101615bf8565b5086821015615c355760001960f88860031b161c19848701351681555b505060018560011b0183555050505050565b6020815260006121926020830184866157e1565b81516001600160401b03811115615c7457615c74615430565b615c8881615c8284546153b7565b84615b41565b6020601f821160018114615cbc5760008315615ca45750848201515b600019600385901b1c1916600184901b1784556139e3565b600084815260208120601f198516915b82811015615cec5787850151825560209485019460019092019101615ccc565b5084821015615d0a5786840151600019600387901b60f8161c191681555b50505050600190811b01905550565b600060ff831680615d2c57615d2c6156c6565b8060ff8416069150509291505056fec1f6fe24621ce81ec5827caf0253cadb74709b061630e6b55e8237170593200052c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0002dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800a164736f6c634300081c000a0000000000000000000000000262e3e15ccfd2221b35d05909222f1f5fcdcd80000000000000000000000000a665b273997f70b647b66fa7ed021287544849db000000000000000000000000279ccf56441fc74f1aac39e7fac165dec5a88b3a00000000000000000000000072f87239981159ed23673012ee3806ca6114ab2a
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106100885760003560e01c806371b0a1091161005b57806371b0a109146101465780639980cb2314610179578063a5e39e8e146101a0578063c42f3d1b146101b357600080fd5b806305111eb91461008d57806321903d79146100d157806354fd4d50146100f8578063608935151461011f575b600080fd5b6100b47f00000000000000000000000072f87239981159ed23673012ee3806ca6114ab2a81565b6040516001600160a01b0390911681526020015b60405180910390f35b6100b47f000000000000000000000000279ccf56441fc74f1aac39e7fac165dec5a88b3a81565b60408051808201825260058152640352e302e360dc1b602082015290516100c891906111c6565b6100b47f000000000000000000000000a665b273997f70b647b66fa7ed021287544849db81565b610159610154366004611256565b6101da565b604080516001600160a01b039384168152929091166020830152016100c8565b6100b47f0000000000000000000000000262e3e15ccfd2221b35d05909222f1f5fcdcd8081565b6101596101ae366004611428565b610989565b6100b47f000000000000000000000000b6b35b2c7032e00baa2535ba480d461321b7e0a681565b60408051336020808301919091528183018490528251808303840181526060909201909252805191012060009081906102d18a8a8a3061021a8a80611526565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506102599250505060208c018c611526565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506102989250505060408d018d611526565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152508b9250610989915050565b6040805160028082526060820190925292955090935060009190816020015b60408051808201909152600080825260208201528152602001906001900390816102f05790505090506001600160a01b038c1661046a576001600160a01b037f00000000000000000000000072f87239981159ed23673012ee3806ca6114ab2a1663c59ee4a96103608d80611576565b6040516020016103719291906115bc565b60408051601f1981840301815291905261038e60208f018f611576565b60405160200161039f9291906115e4565b604051602081830303815290604052878c876040518663ffffffff1660e01b81526004016103d195949392919061171b565b6060604051808303816000875af11580156103f0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104149190611776565b83600081518110610427576104276117c3565b602002602001015160000184600081518110610445576104456117c3565b6020908102919091018101516001600160a01b03938416910152911690529b5061054c565b7f00000000000000000000000072f87239981159ed23673012ee3806ca6114ab2a6001600160a01b031663a7f52023898e856040518463ffffffff1660e01b81526004016104ba939291906117d9565b60408051808303816000875af11580156104d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104fc9190611807565b8260008151811061050f5761050f6117c3565b60200260200101516000018360008151811061052d5761052d6117c3565b6020908102919091018101516001600160a01b03938416910152911690525b6105568680611526565b905060000361070d577f00000000000000000000000072f87239981159ed23673012ee3806ca6114ab2a6001600160a01b031663a7f52023888e85196040518463ffffffff1660e01b81526004016105b0939291906117d9565b60408051808303816000875af11580156105ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105f29190611807565b82600181518110610605576106056117c3565b602002602001015160000183600181518110610623576106236117c3565b6020026020010151602001826001600160a01b03166001600160a01b0316815250826001600160a01b03166001600160a01b03168152505050836001600160a01b0316632f2ff15d7f4ff6ae4d6a29e79ca45c6441bdc89b93878ac6118485b33c8baa3749fc3cb1308360018151811061069f5761069f6117c3565b6020026020010151602001516040518363ffffffff1660e01b81526004016106da9291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b1580156106f457600080fd5b505af1158015610708573d6000803e3d6000fd5b505050505b836001600160a01b0316632f2ff15d6000801b83600081518110610733576107336117c3565b6020026020010151602001516040518363ffffffff1660e01b815260040161076e9291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b15801561078857600080fd5b505af115801561079c573d6000803e3d6000fd5b5050604051631b2b455f60e11b8152600060048201523060248201526001600160a01b03871692506336568abe9150604401600060405180830381600087803b1580156107e857600080fd5b505af11580156107fc573d6000803e3d6000fd5b50505050826001600160a01b031663f2fde38b82600081518110610822576108226117c3565b6020026020010151602001516040518263ffffffff1660e01b815260040161085991906001600160a01b0391909116815260200190565b600060405180830381600087803b15801561087357600080fd5b505af1158015610887573d6000803e3d6000fd5b50505050836001600160a01b03168c6001600160a01b03167f08af36628654870563f8102f737700df4046cdfaef3ff1a7a48253d07e9e1a6b836000815181106108d3576108d36117c3565b602002602001015160000151846000815181106108f2576108f26117c3565b60200260200101516020015185600181518110610911576109116117c3565b60200260200101516000015186600181518110610930576109306117c3565b60200260200101516020015160405161097294939291906001600160a01b03948516815292841660208401529083166040830152909116606082015260800190565b60405180910390a350509850989650505050505050565b60008061099960608b018b611526565b90506109a860408c018c611526565b9050146109c857604051632692258760e11b815260040160405180910390fd5b6000338b8b8b8b8b8b8b6040516020016109e89796959493929190611b0e565b60408051601f1981840301815282825280516020918201206001600160a01b03909416908301528101919091526060810185905260800160405160208183030381529060405280519060200120905080887f000000000000000000000000a665b273997f70b647b66fa7ed021287544849db604051610a6690611166565b6001600160a01b039283168152911660208201526040018190604051809103906000f5905080158015610a9d573d6000803e3d6000fd5b509150807f000000000000000000000000b6b35b2c7032e00baa2535ba480d461321b7e0a683604051610acf90611173565b6001600160a01b039283168152911660208201526040018190604051809103906000f5905080158015610b06573d6000803e3d6000fd5b50925060005b610b1960408d018d611526565b9050811015610b8d57610b85610b3260408e018e611526565b83818110610b4257610b426117c3565b9050602002016020810190610b579190611b9d565b33868f8060600190610b699190611526565b86818110610b7957610b796117c3565b90506020020135611091565b600101610b0c565b506040805180820182526001600160a01b037f0000000000000000000000000262e3e15ccfd2221b35d05909222f1f5fcdcd80811682527f000000000000000000000000279ccf56441fc74f1aac39e7fac165dec5a88b3a811660208301529151632104725560e21b815291851691638411c95491610c16918f918f918f903390600401611bba565b600060405180830381600087803b158015610c3057600080fd5b505af1158015610c44573d6000803e3d6000fd5b50505050826001600160a01b0316632f2ff15d846001600160a01b031663a217fddf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cb99190611c2b565b6040516001600160e01b031960e084901b16815260048101919091526001600160a01b038b166024820152604401600060405180830381600087803b158015610d0157600080fd5b505af1158015610d15573d6000803e3d6000fd5b5050505060005b8751811015610ddc57836001600160a01b0316632f2ff15d7f4ff6ae4d6a29e79ca45c6441bdc89b93878ac6118485b33c8baa3749fc3cb1308a8481518110610d6757610d676117c3565b60200260200101516040518363ffffffff1660e01b8152600401610d9e9291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b158015610db857600080fd5b505af1158015610dcc573d6000803e3d6000fd5b505060019092019150610d1c9050565b5060005b8651811015610ea057836001600160a01b0316632f2ff15d7f13ff1b2625181b311f257c723b5e6d366eb318b212d9dd694c48fcf227659df5898481518110610e2b57610e2b6117c3565b60200260200101516040518363ffffffff1660e01b8152600401610e629291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b158015610e7c57600080fd5b505af1158015610e90573d6000803e3d6000fd5b505060019092019150610de09050565b5060005b8551811015610f6457836001600160a01b0316632f2ff15d7f2d8e650da9bd8c373ab2450d770f2ed39549bfc28d3630025cecc51511bcd374888481518110610eef57610eef6117c3565b60200260200101516040518363ffffffff1660e01b8152600401610f269291909182526001600160a01b0316602082015260400190565b600060405180830381600087803b158015610f4057600080fd5b505af1158015610f54573d6000803e3d6000fd5b505060019092019150610ea49050565b506001600160a01b038816301461103e57826001600160a01b03166336568abe846001600160a01b031663a217fddf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610fc2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fe69190611c2b565b6040516001600160e01b031960e084901b1681526004810191909152306024820152604401600060405180830381600087803b15801561102557600080fd5b505af1158015611039573d6000803e3d6000fd5b505050505b6040516001600160a01b03838116825280851691908a16907f017464e04c545b4f5c5e32a4c60ce4ff586eef58fdda661784f9905bcd764fda9060200160405180910390a3509850989650505050505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b1790526110eb9085906110f1565b50505050565b600080602060008451602086016000885af180611114576040513d6000823e3d81fd5b50506000513d9150811561112c578060011415611139565b6001600160a01b0384163b155b156110eb57604051635274afe760e01b81526001600160a01b038516600482015260240160405180910390fd5b6106d480611c4583390190565b61082c8061231983390190565b6000815180845260005b818110156111a65760208185018101518683018201520161118a565b506000602082860101526020601f19601f83011685010191505092915050565b6020815260006111d96020830184611180565b9392505050565b6001600160a01b03811681146111f557600080fd5b50565b8035611203816111e0565b919050565b600060a0828403121561121a57600080fd5b50919050565b60006080828403121561121a57600080fd5b600060c0828403121561121a57600080fd5b60006060828403121561121a57600080fd5b600080600080600080600080610160898b03121561127357600080fd5b61127c896111f8565b975060208901356001600160401b0381111561129757600080fd5b6112a38b828c01611208565b97505060408901356001600160401b038111156112bf57600080fd5b6112cb8b828c01611208565b9650506112db8a60608b01611220565b945060e08901356001600160401b038111156112f657600080fd5b6113028b828c01611232565b9450506101008901356001600160401b0381111561131f57600080fd5b61132b8b828c01611232565b9350506101208901356001600160401b0381111561134857600080fd5b6113548b828c01611244565b989b979a5095989497939692955092936101400135925050565b634e487b7160e01b600052604160045260246000fd5b600082601f83011261139557600080fd5b81356001600160401b038111156113ae576113ae61136e565b8060051b604051601f19603f83011681018181106001600160401b03821117156113da576113da61136e565b6040529182526020818501810192908101868411156113f857600080fd5b6020860192505b8383101561141e57611410836111f8565b8152602092830192016113ff565b5095945050505050565b600080600080600080600080610160898b03121561144557600080fd5b88356001600160401b0381111561145b57600080fd5b6114678b828c01611208565b98505060208901356001600160401b0381111561148357600080fd5b61148f8b828c01611208565b97505061149f8a60408b01611220565b95506114ad60c08a016111f8565b945060e08901356001600160401b038111156114c857600080fd5b6114d48b828c01611384565b9450506101008901356001600160401b038111156114f157600080fd5b6114fd8b828c01611384565b9350506101208901356001600160401b0381111561151a57600080fd5b6113548b828c01611384565b6000808335601e1984360301811261153d57600080fd5b8301803591506001600160401b0382111561155757600080fd5b6020019150600581901b360382131561156f57600080fd5b9250929050565b6000808335601e1984360301811261158d57600080fd5b8301803591506001600160401b038211156115a757600080fd5b60200191503681900382131561156f57600080fd5b6b02b37ba3296a637b1b5b2b2160a51b81528183600c83013760009101600c01908152919050565b61159360f21b81528183600283013760009101600201908152919050565b6000808335601e1984360301811261161957600080fd5b83016020810192503590506001600160401b0381111561163857600080fd5b8060051b360382131561156f57600080fd5b81835260208301925060008160005b8481101561168a57813561166c816111e0565b6001600160a01b031686526020958601959190910190600101611659565b5093949350505050565b6000813565ffffffffffff81168082146116ad57600080fd5b845250602082013563ffffffff811681146116c757600080fd5b63ffffffff1660208401526040828101359084015260608083013590840152608080830135908401526116fd60a0830183611602565b60c060a086015261171260c08601828461164a565b95945050505050565b60a08152600061172e60a0830188611180565b82810360208401526117408188611180565b6001600160a01b0387166040850152838103606085015290506117638186611694565b9150508260808301529695505050505050565b60008060006060848603121561178b57600080fd5b8351611796816111e0565b60208501519093506117a7816111e0565b60408501519092506117b8816111e0565b809150509250925092565b634e487b7160e01b600052603260045260246000fd5b6060815260006117ec6060830186611694565b6001600160a01b039490941660208301525060400152919050565b6000806040838503121561181a57600080fd5b8251611825816111e0565b6020840151909250611836816111e0565b809150509250929050565b6000808335601e1984360301811261185857600080fd5b83016020810192503590506001600160401b0381111561187757600080fd5b80360382131561156f57600080fd5b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60006118bb8283611841565b60a085526118cd60a086018284611886565b9150506118dd6020840184611841565b85830360208701526118f0838284611886565b925050506119016040840184611602565b858303604087015261191483828461164a565b925050506119256060840184611602565b85830360608701528083526001600160fb1b0381111561194457600080fd5b60051b80826020850137608094850135959094019490945290910160200192915050565b81835260208301925060008160005b8481101561168a57813561198a816111e0565b6001600160a01b0316865260208201356bffffffffffffffffffffffff81168082146119b557600080fd5b6020880152506040958601959190910190600101611977565b803582526000602082013536839003601e190181126119ec57600080fd5b82016020810190356001600160401b03811115611a0857600080fd5b8060061b3603821315611a1a57600080fd5b60a06020860152611a2f60a086018284611968565b60408581013590870152606080860135908701529150611a5490506080840184611841565b8583036080870152611a67838284611886565b9695505050505050565b8035801515811461120357600080fd5b611a8a81611a71565b15158252611a9a60208201611a71565b15156020830152604081013560038110158015611ab657600080fd5b506040830152611ac860608201611a71565b151560608301525050565b600081518084526020840193506020830160005b8281101561168a5781516001600160a01b0316865260209586019590910190600101611ae7565b61014081526000611b2361014083018a6118af565b8281036020840152611b35818a6119ce565b9050611b446040840189611a81565b6001600160a01b03871660c084015282810360e0840152611b658187611ad3565b9050828103610100840152611b7a8186611ad3565b9050828103610120840152611b8f8185611ad3565b9a9950505050505050505050565b600060208284031215611baf57600080fd5b81356111d9816111e0565b61012081526000611bcf6101208301886118af565b8281036020840152611be181886119ce565b86516001600160a01b03908116604086015260208801511660608501529150611c0f90506080830185611a81565b6001600160a01b03929092166101009190910152949350505050565b600060208284031215611c3d57600080fd5b505191905056fe60a060405234801561001057600080fd5b506040516106d43803806106d483398101604081905261002f916100e6565b816001600160a01b03811661005e57604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b6100678161007a565b506001600160a01b031660805250610119565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b80516001600160a01b03811681146100e157600080fd5b919050565b600080604083850312156100f957600080fd5b610102836100ca565b9150610110602084016100ca565b90509250929050565b60805161059a61013a6000396000818160610152610111015261059a6000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c8063608935151461005c578063715018a61461009f57806386e5ab2e146100a95780638da5cb5b146100bc578063f2fde38b146100cd575b600080fd5b6100837f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200160405180910390f35b6100a76100e0565b005b6100a76100b73660046103f8565b6100f4565b6000546001600160a01b0316610083565b6100a76100db3660046104cd565b61030d565b6100e8610350565b6100f2600061037d565b565b6100fc610350565b6040516237935760e61b8152600481018390527f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b03821690630de4d5c090602401602060405180830381865afa158015610162573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061018691906104f1565b156101a45760405163639c421d60e01b815260040160405180910390fd5b604051633740401760e01b8152600481018490526000906001600160a01b03831690633740401790602401602060405180830381865afa1580156101ec573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102109190610513565b6001600160a01b0316036102375760405163a9146eeb60e01b815260040160405180910390fd5b604051632777202560e11b8152600481018490526000906001600160a01b03831690634eee404a90602401602060405180830381865afa15801561027f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102a39190610513565b60405163278f794360e11b81529091506001600160a01b03861690634f1ef286906102d49084908790600401610530565b600060405180830381600087803b1580156102ee57600080fd5b505af1158015610302573d6000803e3d6000fd5b505050505050505050565b610315610350565b6001600160a01b03811661034457604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b61034d8161037d565b50565b6000546001600160a01b031633146100f25760405163118cdaa760e01b815233600482015260240161033b565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b038116811461034d57600080fd5b634e487b7160e01b600052604160045260246000fd5b60008060006060848603121561040d57600080fd5b8335610418816103cd565b925060208401359150604084013567ffffffffffffffff81111561043b57600080fd5b8401601f8101861361044c57600080fd5b803567ffffffffffffffff811115610466576104666103e2565b604051601f8201601f19908116603f0116810167ffffffffffffffff81118282101715610495576104956103e2565b6040528181528282016020018810156104ad57600080fd5b816020840160208301376000602083830101528093505050509250925092565b6000602082840312156104df57600080fd5b81356104ea816103cd565b9392505050565b60006020828403121561050357600080fd5b815180151581146104ea57600080fd5b60006020828403121561052557600080fd5b81516104ea816103cd565b60018060a01b0383168152604060208201526000825180604084015260005b8181101561056c576020818601810151606086840101520161054f565b506000606082850101526060601f19601f830116840101915050939250505056fea164736f6c634300081c000a608060405234801561001057600080fd5b5060405161082c38038061082c83398101604081905261002f91610324565b604080516020810190915260008152829061004a828261005d565b506100569050816100bc565b5050610386565b6100668261012a565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a28051156100b0576100ab82826101a9565b505050565b6100b8610220565b5050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6100fc60008051602061080c833981519152546001600160a01b031690565b604080516001600160a01b03928316815291841660208301520160405180910390a161012781610241565b50565b806001600160a01b03163b60000361016557604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5b80546001600160a01b0319166001600160a01b039290921691909117905550565b6060600080846001600160a01b0316846040516101c69190610357565b600060405180830381855af49150503d8060008114610201576040519150601f19603f3d011682016040523d82523d6000602084013e610206565b606091505b509092509050610217858383610280565b95945050505050565b341561023f5760405163b398979f60e01b815260040160405180910390fd5b565b6001600160a01b03811661026b57604051633173bdd160e11b81526000600482015260240161015c565b8060008051602061080c833981519152610188565b60608261029557610290826102df565b6102d8565b81511580156102ac57506001600160a01b0384163b155b156102d557604051639996b31560e01b81526001600160a01b038516600482015260240161015c565b50805b9392505050565b8051156102ef5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b80516001600160a01b038116811461031f57600080fd5b919050565b6000806040838503121561033757600080fd5b61034083610308565b915061034e60208401610308565b90509250929050565b6000825160005b81811015610378576020818601810151858301520161035e565b506000920191825250919050565b610477806103956000396000f3fe608060405261000c61000e565b005b610016610091565b6001600160a01b03163303610087576000356001600160e01b03191663278f794360e11b14610058576040516334ad5dbb60e21b815260040160405180910390fd5b6000806100683660048184610323565b8101906100759190610363565b9150915061008382826100c4565b5050565b61008f61011f565b565b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b546001600160a01b0316919050565b6100cd8261012f565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a28051156101175761011282826101ab565b505050565b610083610221565b61008f61012a610240565b61024f565b806001600160a01b03163b60000361016a57604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060600080846001600160a01b0316846040516101c8919061043b565b600060405180830381855af49150503d8060008114610203576040519150601f19603f3d011682016040523d82523d6000602084013e610208565b606091505b5091509150610218858383610273565b95945050505050565b341561008f5760405163b398979f60e01b815260040160405180910390fd5b600061024a6102d2565b905090565b3660008037600080366000845af43d6000803e80801561026e573d6000f35b3d6000fd5b60608261028857610283826102fa565b6102cb565b815115801561029f57506001600160a01b0384163b155b156102c857604051639996b31560e01b81526001600160a01b0385166004820152602401610161565b50805b9392505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc6100b5565b80511561030a5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b6000808585111561033357600080fd5b8386111561034057600080fd5b5050820193919092039150565b634e487b7160e01b600052604160045260246000fd5b6000806040838503121561037657600080fd5b82356001600160a01b038116811461038d57600080fd5b9150602083013567ffffffffffffffff8111156103a957600080fd5b8301601f810185136103ba57600080fd5b803567ffffffffffffffff8111156103d4576103d461034d565b604051601f8201601f19908116603f0116810167ffffffffffffffff811182821017156104035761040361034d565b60405281815282820160200187101561041b57600080fd5b816020840160208301376000602083830101528093505050509250929050565b6000825160005b8181101561045c5760208186018101518583015201610442565b50600092019182525091905056fea164736f6c634300081c000ab53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103a164736f6c634300081c000a
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000000262e3e15ccfd2221b35d05909222f1f5fcdcd80000000000000000000000000a665b273997f70b647b66fa7ed021287544849db000000000000000000000000279ccf56441fc74f1aac39e7fac165dec5a88b3a00000000000000000000000072f87239981159ed23673012ee3806ca6114ab2a
-----Decoded View---------------
Arg [0] : _daoFeeRegistry (address): 0x0262E3e15cCFD2221b35D05909222f1f5FCdcd80
Arg [1] : _versionRegistry (address): 0xA665b273997F70b647B66fa7Ed021287544849dB
Arg [2] : _trustedFillerRegistry (address): 0x279ccF56441fC74f1aAC39E7faC165Dec5A88B3A
Arg [3] : _governanceDeployer (address): 0x72f87239981159ed23673012EE3806Ca6114AB2A
-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 0000000000000000000000000262e3e15ccfd2221b35d05909222f1f5fcdcd80
Arg [1] : 000000000000000000000000a665b273997f70b647b66fa7ed021287544849db
Arg [2] : 000000000000000000000000279ccf56441fc74f1aac39e7fac165dec5a88b3a
Arg [3] : 00000000000000000000000072f87239981159ed23673012ee3806ca6114ab2a
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 33 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ 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.