Feature Tip: Add private address tag to any address under My Name Tag !
ERC-20
Overview
Max Total Supply
23.285735863729547864 NapierPool LPT
Holders
556
Market
Onchain Market Cap
$0.00
Circulating Supply Market Cap
-
Other Info
Token Contract (WITH 18 Decimals)
Balance
2.557333678985868698 NapierPool LPTValue
$0.00Loading...
Loading
Loading...
Loading
Loading...
Loading
# | Exchange | Pair | Price | 24H Volume | % Volume |
---|
Contract Name:
NapierPool
Compiler Version
v0.8.19+commit.7dd6d404
Optimization Enabled:
Yes with 500 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.19; // interfaces import {IERC20} from "@openzeppelin/[email protected]/token/ERC20/IERC20.sol"; import {ITranche} from "@napier/v1-tranche/src/interfaces/ITranche.sol"; import {CurveTricryptoOptimizedWETH} from "./interfaces/external/CurveTricryptoOptimizedWETH.sol"; import {INapierPool} from "./interfaces/INapierPool.sol"; import {INapierSwapCallback} from "./interfaces/INapierSwapCallback.sol"; import {INapierMintCallback} from "./interfaces/INapierMintCallback.sol"; import {IPoolFactory} from "./interfaces/IPoolFactory.sol"; // libs import {SafeCast} from "@openzeppelin/[email protected]/utils/math/SafeCast.sol"; import {SafeERC20} from "@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol"; import {Math} from "@openzeppelin/[email protected]/utils/math/Math.sol"; import {PoolMath, PoolState} from "./libs/PoolMath.sol"; import {SignedMath} from "./libs/SignedMath.sol"; import {DecimalConversion} from "./libs/DecimalConversion.sol"; import {MAX_LN_FEE_RATE_ROOT, MAX_PROTOCOL_FEE_PERCENT} from "./libs/Constants.sol"; import {Errors} from "./libs/Errors.sol"; // inherits import {ERC20} from "@openzeppelin/[email protected]/token/ERC20/ERC20.sol"; import {ERC20Permit} from "@openzeppelin/[email protected]/token/ERC20/extensions/ERC20Permit.sol"; import {ReentrancyGuard} from "@openzeppelin/[email protected]/security/ReentrancyGuard.sol"; /// @dev NapierPool is a pool that allows users to trade between a BasePool LP token and an underlying asset. /// BasePool LP token is a token that represents a share of basket of 3 Principal Tokens Curve V2 pool. /// /// Note: This pool and its math assumes the following regarding BasePool: /// 1. The BasePool assets are 3 Napier Principal Tokens (PT) of the same maturity and same underlying asset. /// We can consider BasePool LP token as something like ETF of 3 PTs. /// 2. BasePool LP token is approximately three times more valuable than 1 PT because the initial deposit on Curve pool issues 1:1:1:1=pt1:pt2:pt3:share. /// e.g. When the initial price of PT1, PT2 and PT3 is 1,`1` BasePool LP token is convertible to `1` PT1 + `1` PT2 + `1` PT3 instead of `1/3` for each PT. /// We need to adjust the balance of BasePool LP token by multiplying 3 to make it comparable to underlying asset. /// Economically at maturity 1/3 BaseLP token is expected to be convertible to approximately 1 underlying asset. /// 3. BasePool LP token has 18 decimals. /// 4. PTs have the same decimals as underlying asset. contract NapierPool is INapierPool, ReentrancyGuard, ERC20Permit { using PoolMath for PoolState; using SafeERC20 for IERC20; using SafeERC20 for CurveTricryptoOptimizedWETH; using SignedMath for uint256; using SafeCast for uint256; using DecimalConversion for uint256; uint256 internal constant WAD = 1e18; /// @dev Number of coins in the BasePool uint256 internal constant N_COINS = 3; /// @notice The factory that deployed this pool. IPoolFactory public immutable factory; /// @notice BasePool LP token i.e. Curve v2 3assets pool CurveTricryptoOptimizedWETH public immutable tricrypto; /// @notice Underlying asset (e.g. DAI, WETH) IERC20 public immutable underlying; uint8 internal immutable uDecimals; /// @notice Napier Principal Tokens /// @dev We don't use static size array here because Solidity doesn't support immutable static size array. /// @dev This would significantly reduce gas cost by avoiding SLOAD. About 2000 gas per reading principal token. (cold) /// @dev pt_i is the i-th asset of the BasePool coins. i.e pt[i] = CurveV2Pool.coins(i) IERC20 internal immutable pt1; IERC20 internal immutable pt2; IERC20 internal immutable pt3; /// @notice Maturity of the pool in unix timestamp /// @notice At or after maturity, the pool will no longer accept any liquidity provision or swap. Removing liquidity is still allowed. /// @dev Users can still swap, add or remove liquidity even after maturity on Curve pool. /// @dev expiry of the pool. This is the maturity of all principal tokens in the pool. uint256 public immutable maturity; /// @notice AMM parameter: Scalar root of the pool /// @dev adjust the capital efficiency of the market. uint256 public immutable scalarRoot; /// @notice AMM parameter: Initial anchor of the pool /// @dev initial rate anchor to anchor the market’s formula to be more capital efficient around a certain interest rate. int256 public immutable initialAnchor; /// @notice Recipient of the protocol fee address public immutable feeRecipient; /// @notice AMM parameter: Logarithmic fee rate root of the pool /// @dev Fees rate in terms of interest rate uint80 internal lnFeeRateRoot; /// @notice AMM parameter: Fee Napier charges for swaps in percentage (100=100%) uint8 internal protocolFeePercent; /// @notice AMM parameter: Last logarithmic implied rate of the pool uint256 public lastLnImpliedRate; /// @notice Total amount of BaseLpt in the pool (Reserve) uint128 public totalBaseLpt; /// @notice Total amount of underlying in the pool (Reserve) uint128 public totalUnderlying; /// @dev Revert if maturity is reached modifier notExpired() { if (maturity <= block.timestamp) revert Errors.PoolExpired(); _; } constructor() payable ERC20("Napier Pool LP Token", "NapierPool LPT") ERC20Permit("Napier Pool LP Token") { factory = IPoolFactory(msg.sender); IPoolFactory.InitArgs memory args = factory.args(); // Set mutable variables protocolFeePercent = args.configs.protocolFeePercent; // Set immutable variables scalarRoot = args.configs.scalarRoot; initialAnchor = args.configs.initialAnchor; lnFeeRateRoot = args.configs.lnFeeRateRoot; feeRecipient = args.configs.feeRecipient; address basePool = args.assets.basePool; tricrypto = CurveTricryptoOptimizedWETH(basePool); ERC20 _underlying = ERC20(args.assets.underlying); underlying = _underlying; uDecimals = _underlying.decimals(); // hack: we don't use static size array here to save gas cost ITranche _pt1 = ITranche(args.assets.principalTokens[0]); ITranche _pt2 = ITranche(args.assets.principalTokens[1]); ITranche _pt3 = ITranche(args.assets.principalTokens[2]); pt1 = _pt1; pt2 = _pt2; pt3 = _pt3; // Assume that the maturity of all principal tokens are the same maturity = _pt1.maturity(); // Approve Curve pool to transfer PTs _pt1.approve(basePool, type(uint256).max); // dev: Principal token will revert if failed to approve _pt2.approve(basePool, type(uint256).max); _pt3.approve(basePool, type(uint256).max); } //////////////////////////////////////////////////////////////////////////////// // Mutative functions //////////////////////////////////////////////////////////////////////////////// /// @inheritdoc INapierPool /// @notice Provide BasePoolLpToken (BaseLpt) and underlying in exchange for Lp token, which will grant LP holders more exchange fee over time /// @dev Mint as much LP token as possible. /// @dev BaseLpt and Underlying should be transferred to this contract prior to calling /// @dev Revert if maturity is reached /// @dev Revert if deposited assets are too small to mint more than minimum liquidity /// @dev Revert if deposited assets are too small to compute ln implied rate /// @dev Revert if computed initial exchange rate in base LP token is below one. (deposited base LP token is much less than deposited underlying) /// @dev Revert if proportion of deposited base LP token is higher than the maximum proportion. (deposited base LP token is too large compared to deposited underlying) /// @dev Revert if minted LP token is zero /// @param recipient recipient of the minted LP token /// @return liquidity amount of LP token minted function addLiquidity(uint256 underlyingInDesired, uint256 baseLptInDesired, address recipient, bytes memory data) external override nonReentrant notExpired returns (uint256) { // Cache state variables (uint256 _totalUnderlying, uint256 _totalBaseLpt) = (totalUnderlying, totalBaseLpt); uint256 bBalance = _balance(tricrypto); // Base Pool LP token reserve uint256 uBalance = _balance(underlying); // NOTE: Sum of underlying asset reserve and stuck protocol fees. (uint256 liquidity, uint256 underlyingUsed, uint256 baseLptUsed) = _mintLiquidity(_totalUnderlying, _totalBaseLpt, recipient, underlyingInDesired, baseLptInDesired); /// WRITE /// // Last ln implied rate doesn't change because liquidity is added proportionally totalUnderlying = (_totalUnderlying + underlyingUsed).toUint128(); totalBaseLpt = (_totalBaseLpt + baseLptUsed).toUint128(); /// INTERACTION /// if (!factory.isCallbackReceiverAuthorized(msg.sender)) revert Errors.PoolUnauthorizedCallback(); INapierMintCallback(msg.sender).mintCallback(underlyingUsed, baseLptUsed, data); /// CHECK /// if (_balance(tricrypto) < bBalance + baseLptUsed) revert Errors.PoolInsufficientBaseLptReceived(); if (_balance(underlying) < uBalance + underlyingUsed) { revert Errors.PoolInsufficientUnderlyingReceived(); } return liquidity; } /// @notice Mint LP token for the given amount of underlying and base LP token /// @dev This function doesn't update state variables except Lp token and last implied rate. /// @dev *variableName*18 represents the value *in 18 decimals*. /// @dev Mint as much LP token as possible. /// @dev If the pool is not initialized, a portion of issued LP token will be permanently locked. /// @dev Revert if minted LP token is zero /// @param totalUnderlyingCache total underlying balance of the pool in underlying unit. /// @param totalBaseLptCache total base LP token balance of the pool **(All BaseLpt has 18 decimals)** /// @param recipient recipient of the minted LP token /// @param underlyingIn deposited underlying **in underlying unit** /// @param baseLptIn deposited base LP token **(All BaseLpt has 18 decimals)** /// @return liquidity - amount of LP token minted /// @return underlyingUsed - amount of underlying used /// @return baseLptUsed - amount of base LP token used function _mintLiquidity( uint256 totalUnderlyingCache, uint256 totalBaseLptCache, address recipient, uint256 underlyingIn, uint256 baseLptIn ) internal returns (uint256 liquidity, uint256 underlyingUsed, uint256 baseLptUsed) { uint256 totalLp = totalSupply(); if (totalLp == 0) { // Note: This path is executed only once. // Amounts of underlying is converted to 18 decimals to normalize how much LP token is issued. liquidity = Math.sqrt(underlyingIn.to18Decimals(uDecimals) * baseLptIn) - PoolMath.MINIMUM_LIQUIDITY; underlyingUsed = underlyingIn; baseLptUsed = baseLptIn; /// WRITE // Note: Only at initial issuance, a portion of the issued LP tokens will be permanently locked. uint256 virtualPrice = tricrypto.get_virtual_price(); _mint(address(1), PoolMath.MINIMUM_LIQUIDITY); lastLnImpliedRate = PoolMath.computeInitialLnImpliedRate( PoolState({ totalBaseLptTimesN: baseLptUsed * N_COINS * virtualPrice / WAD, totalUnderlying18: underlyingUsed.to18Decimals(uDecimals), virtualPrice: virtualPrice, scalarRoot: scalarRoot, maturity: maturity, lnFeeRateRoot: lnFeeRateRoot, protocolFeePercent: protocolFeePercent, lastLnImpliedRate: 0 }), initialAnchor ); emit UpdateLnImpliedRate(lastLnImpliedRate); } else { // Note: Multiplying `N_COINS * virtual_price` is not needed because it is canceled out thanks to ratio calculation. uint256 netLpByBaseLpt = (baseLptIn * totalLp) / totalBaseLptCache; uint256 netLpByUnderlying = (underlyingIn * totalLp) / totalUnderlyingCache; if (netLpByBaseLpt < netLpByUnderlying) { liquidity = netLpByBaseLpt; baseLptUsed = baseLptIn; underlyingUsed = (totalUnderlyingCache * liquidity) / totalLp; } else { liquidity = netLpByUnderlying; underlyingUsed = underlyingIn; baseLptUsed = (totalBaseLptCache * liquidity) / totalLp; } } /// WRITE // Mint LP token to recipient if (liquidity == 0) revert Errors.PoolZeroAmountsOutput(); _mint(recipient, liquidity); emit Mint(recipient, liquidity, underlyingUsed, baseLptUsed); } /// @inheritdoc INapierPool /// @notice Burn Lp token in exchange for underlying and base LP token. /// @dev liquidity token (Lp token) should be transferred to this contract prior to calling this function /// @dev Revert if underlying and base LP token are zero /// @dev Revert if liquidity to burn is zero /// @param recipient recipient of the withdrawn underlying and base LP token /// @return underlyingOut amount of underlying withdrawn /// @return baseLptOut amount of base LP token withdrawn function removeLiquidity(address recipient) external override nonReentrant returns (uint256 underlyingOut, uint256 baseLptOut) { uint256 liquidity = balanceOf(address(this)); (uint256 _totalUnderlying, uint256 _totalBaseLpt) = (totalUnderlying, totalBaseLpt); (underlyingOut, baseLptOut) = _burnLiquidity(totalUnderlying, totalBaseLpt, liquidity); if (underlyingOut == 0 && baseLptOut == 0) revert Errors.PoolZeroAmountsOutput(); /// WRITE /// totalUnderlying = (_totalUnderlying - underlyingOut).toUint128(); totalBaseLpt = (_totalBaseLpt - baseLptOut).toUint128(); /// INTERACTION /// underlying.safeTransfer(recipient, underlyingOut); tricrypto.safeTransfer(recipient, baseLptOut); emit Burn(recipient, liquidity, underlyingOut, baseLptOut); } /// @notice Burn Lp token in exchange for underlying and Base LP token. /// @dev This function doesn't update state variables except Lp token. /// @dev *variableName*18 represents the value *in 18 decimals*. /// @dev Not revert even if `underlyingOut18` and `baseLptOut` are zero /// @param totalUnderlyingCache total underlying balance of the pool **in 18 decimals**. /// @param totalBaseLptCache total Base LP token balance of the pool **(All BaseLpt has 18 decimals)** /// @param liquidity amount of LP token to burn /// @return underlyingOut - amount of underlying withdrawn **in 18 decimals** /// @return baseLptOut - amount of Base LP token withdrawn function _burnLiquidity(uint256 totalUnderlyingCache, uint256 totalBaseLptCache, uint256 liquidity) internal returns (uint256 underlyingOut, uint256 baseLptOut) { if (liquidity == 0) revert Errors.PoolZeroAmountsInput(); uint256 totalLp = totalSupply(); underlyingOut = (liquidity * totalUnderlyingCache) / totalLp; baseLptOut = (liquidity * totalBaseLptCache) / totalLp; _burn(address(this), liquidity); } /// @inheritdoc INapierPool /// @notice Swap exact amount of PT for underlying token /// @dev Revert if maturity is reached /// @dev Revert if index is invalid /// @dev Revert if callback recipient is not authorized /// @dev Revert if ptIn is too large and runs out of underlying reserve /// @dev Revert if minted base Lp token is less than expected. (pt is not enough to mint expected base Lp token amount) /// @param index index of the PT token /// @param ptIn amount of PT token to swap /// @param recipient recipient of the underlying token and receiver of callback function /// @param data data to pass to the recipient on callback. If empty, no callback. /// @return underlyingOut amount of underlying token out function swapPtForUnderlying(uint256 index, uint256 ptIn, address recipient, bytes calldata data) external override nonReentrant notExpired returns (uint256 underlyingOut) { uint256[3] memory amountsIn; uint256 exactBaseLptIn; uint256 swapFee; uint256 protocolFee; // stack too deep { PoolState memory state = _loadState(); // Pre-compute the swap result given principal token amountsIn[index] = ptIn; exactBaseLptIn = tricrypto.calc_token_amount(amountsIn, true); // Pre-compute the swap result given BaseLpt and underlying (uint256 underlyingOut18, uint256 swapFee18, uint256 protocolFee18) = state.swapExactBaseLpTokenForUnderlying(exactBaseLptIn); underlyingOut = underlyingOut18.from18Decimals(uDecimals); swapFee = swapFee18.from18Decimals(uDecimals); protocolFee = protocolFee18.from18Decimals(uDecimals); // dev: If `underlyingOut18` is less than 10**(18 - underlyingDecimals), `underlyingOut` will be zero. // Revert to prevent users from swapping non-zero amount of BaseLpt for 0 underlying. if (underlyingOut == 0) revert Errors.PoolZeroAmountsOutput(); /// WRITE /// _writeState(state); } { uint256 bBalance = _balance(tricrypto); // Base Pool LP token reserve uint256 uBalance = _balance(underlying); // NOTE: Sum of underlying asset reserve and stuck protocol fees. /// INTERACTION /// // dev: Optimistically transfer underlying to recipient underlying.safeTransfer(recipient, underlyingOut); // incoming to user => positive, outgoing from user => negative if (!factory.isCallbackReceiverAuthorized(msg.sender)) revert Errors.PoolUnauthorizedCallback(); INapierSwapCallback(msg.sender).swapCallback(underlyingOut.toInt256(), ptIn.neg(), data); // Curve pool will revert if we don't receive enough principal token at this point // Deposit the principal token which `msg.sender` should send in the callback to BasePool tricrypto.add_liquidity(amountsIn, 0); // unlimited slippage /// CHECK /// // Revert if we don't receive enough baseLpt if (_balance(tricrypto) < bBalance + exactBaseLptIn) revert Errors.PoolInsufficientBaseLptReceived(); if (_balance(underlying) < uBalance - underlyingOut) { revert Errors.PoolInvariantViolated(); } } emit Swap(msg.sender, recipient, underlyingOut.toInt256(), index, ptIn.neg(), swapFee, protocolFee); } /// @inheritdoc INapierPool /// @notice Swap underlying token for approximately exact amount of PT /// @notice This function can NOT swap underlying for *exact* amount of PT due to approximation error on Curve pool. /// Revert if maturity is reached /// Revert if index is invalid /// Revert if callback recipient is not authorized /// Revert if ptOutDesired is too large and runs out of pt reserve in Base pool /// Revert if underlying received is less than expected. /// @param index index of the PT /// @param ptOutDesired amount of PT to be swapped out /// @param recipient recipient of the PT and receiver of callback function /// @param data data to pass to the recipient on callback /// callback can be invoked by only authorized contract function swapUnderlyingForPt(uint256 index, uint256 ptOutDesired, address recipient, bytes calldata data) external override nonReentrant notExpired returns (uint256 underlyingIn) { uint256 exactBaseLptOut; uint256 swapFee; uint256 protocolFee; // Pre-compute the swap result // stack too deep { PoolState memory state = _loadState(); uint256[3] memory ptsOut; ptsOut[index] = ptOutDesired; exactBaseLptOut = tricrypto.calc_token_amount(ptsOut, false); // Pre-compute the swap result given BaseLpt (uint256 underlyingIn18, uint256 swapFee18, uint256 protocolFee18) = state.swapUnderlyingForExactBaseLpToken(exactBaseLptOut); underlyingIn = underlyingIn18.from18Decimals(uDecimals); swapFee = swapFee18.from18Decimals(uDecimals); protocolFee = protocolFee18.from18Decimals(uDecimals); // dev: If `underlyingIn18` is less than 10**(18 - underlyingDecimals), `underlyingIn` will be zero. // Revert to prevent users from swapping for free. if (underlyingIn == 0) revert Errors.PoolZeroAmountsInput(); /// WRITE /// _writeState(state); } uint256 bBalance = _balance(tricrypto); // Base Pool LP token reserve uint256 uBalance = _balance(underlying); // NOTE: Sum of underlying asset reserve and stuck protocol fees. /// INTERACTION /// // Remove the principal token from BasePool with minimum = 0 uint256 ptOutActual = tricrypto.remove_liquidity_one_coin(exactBaseLptOut, index, 0, false, recipient); // incoming to user => positive, outgoing from user => negative if (!factory.isCallbackReceiverAuthorized(msg.sender)) revert Errors.PoolUnauthorizedCallback(); INapierSwapCallback(msg.sender).swapCallback(underlyingIn.neg(), ptOutActual.toInt256(), data); /// CHECK /// // Revert if we don't receive enough underlying if (_balance(underlying) < uBalance + underlyingIn) { revert Errors.PoolInsufficientUnderlyingReceived(); } if (_balance(tricrypto) < bBalance - exactBaseLptOut) { revert Errors.PoolInvariantViolated(); } emit Swap(msg.sender, recipient, underlyingIn.neg(), index, ptOutActual.toInt256(), swapFee, protocolFee); } /// @inheritdoc INapierPool /// @notice Swap underlying token for exact amount of Base Lp token /// @notice Approve this contract to use underlying prior to calling this function. /// @dev Revert if maturity is reached function swapUnderlyingForExactBaseLpToken(uint256 baseLptOut, address recipient) external override nonReentrant notExpired returns (uint256) { PoolState memory state = _loadState(); (uint256 underlyingIn18, uint256 swapFee18, uint256 protocolFee18) = state.swapUnderlyingForExactBaseLpToken(baseLptOut); uint256 underlyingIn = underlyingIn18.from18Decimals(uDecimals); uint256 swapFee = swapFee18.from18Decimals(uDecimals); uint256 protocolFee = protocolFee18.from18Decimals(uDecimals); // dev: If `underlyingIn18` is less than 10**(18 - underlyingDecimals), `underlyingIn` will be zero. // Revert to prevent users from swapping for free. if (underlyingIn == 0) revert Errors.PoolZeroAmountsInput(); /// WRITE /// _writeState(state); /// INTERACTION /// underlying.safeTransferFrom(msg.sender, address(this), underlyingIn); tricrypto.safeTransfer(recipient, baseLptOut); emit SwapBaseLpt(msg.sender, recipient, -(underlyingIn.toInt256()), baseLptOut.toInt256(), swapFee, protocolFee); return underlyingIn; } /// @inheritdoc INapierPool /// @notice Swap exact amount of Base Lp token for underlying token /// @notice Approve this contract to use BaseLP token prior to calling this function. /// @dev Revert if maturity is reached function swapExactBaseLpTokenForUnderlying(uint256 baseLptIn, address recipient) external override nonReentrant notExpired returns (uint256) { PoolState memory state = _loadState(); (uint256 underlyingOut18, uint256 swapFee18, uint256 protocolFee18) = state.swapExactBaseLpTokenForUnderlying(baseLptIn); uint256 underlyingOut = underlyingOut18.from18Decimals(uDecimals); uint256 swapFee = swapFee18.from18Decimals(uDecimals); uint256 protocolFee = protocolFee18.from18Decimals(uDecimals); // dev: If `underlyingOut18` is less than 10**(18 - underlyingDecimals), `underlyingOut` will be zero. // Revert to prevent users from swapping non-zero amount of BaseLpt for 0 underlying. if (underlyingOut == 0) revert Errors.PoolZeroAmountsOutput(); /// WRITE /// _writeState(state); /// INTERACTION /// tricrypto.safeTransferFrom(msg.sender, address(this), baseLptIn); underlying.safeTransfer(recipient, underlyingOut); emit SwapBaseLpt(msg.sender, recipient, underlyingOut.toInt256(), baseLptIn.neg(), swapFee, protocolFee); return underlyingOut; } /// @notice Forcibly sweep excess tokens to the fee recipient /// @notice This function can be called by anyone /// @notice Protocol fee is sent to the fee recipient /// @dev Excess tokens (excluding fees) can be swept by anyone, using `addLiquidity` etc. /// @dev Can be used when the pool is in an inconsistent state: /// A large amount of base LP token or underlying is donated to the pool, which makes the pool revert when swapping base LP token for underlying /// because the pool doesn't have enough underlying to swap. function skim() external nonReentrant { (uint256 _totalUnderlying, uint256 _totalBaseLpt) = (totalUnderlying, totalBaseLpt); uint256 baseLptExcess = _balance(tricrypto) - _totalBaseLpt; uint256 feesAndExcess = _balance(underlying) - _totalUnderlying; if (baseLptExcess != 0) tricrypto.safeTransfer(feeRecipient, baseLptExcess); if (feesAndExcess != 0) underlying.safeTransfer(feeRecipient, feesAndExcess); } //////////////////////////////////////////////////////////////////////////////// // Protected functions //////////////////////////////////////////////////////////////////////////////// /// @notice Set fee parameters /// @notice Only the factory owner can call this function. /// @param paramName name of the parameter to set (lnFeeRateRoot, protocolFeePercent) /// @param value value of the parameter function setFeeParameter(bytes32 paramName, uint256 value) external { if (factory.owner() != msg.sender) revert Errors.PoolOnlyOwner(); if (paramName == "lnFeeRateRoot") { if (value > MAX_LN_FEE_RATE_ROOT) revert Errors.LnFeeRateRootTooHigh(); lnFeeRateRoot = uint80(value); // unsafe cast here is Okay because we checked the value is less than MAX_LN_FEE_RATE_ROOT } else if (paramName == "protocolFeePercent") { if (value > MAX_PROTOCOL_FEE_PERCENT) revert Errors.ProtocolFeePercentTooHigh(); protocolFeePercent = uint8(value); // unsafe cast here is Okay } else { revert Errors.PoolInvalidParamName(); } } //////////////////////////////////////////////////////////////////////////////// // View functions //////////////////////////////////////////////////////////////////////////////// /// @notice get Principal Tokens within the pool function principalTokens() public view returns (IERC20[3] memory) { return [pt1, pt2, pt3]; } /// @notice read the state of the pool function readState() external view returns (PoolState memory) { return _loadState(); } /// @notice get underlying and tricrypto addresses of the pool function getAssets() public view returns (address, address) { return (address(underlying), address(tricrypto)); } //////////////////////////////////////////////////////////////////////////////// // Util //////////////////////////////////////////////////////////////////////////////// /// @notice read the state of the pool from storage into memory function _loadState() internal view returns (PoolState memory state) { uint256 virtualPrice = tricrypto.get_virtual_price(); state = PoolState({ totalBaseLptTimesN: uint256(totalBaseLpt) * N_COINS * virtualPrice / WAD, totalUnderlying18: uint256(totalUnderlying).to18Decimals(uDecimals), virtualPrice: virtualPrice, lnFeeRateRoot: lnFeeRateRoot, protocolFeePercent: protocolFeePercent, scalarRoot: scalarRoot, maturity: maturity, lastLnImpliedRate: lastLnImpliedRate }); } /// @notice write back the state of the pool from memory to storage function _writeState(PoolState memory state) internal { lastLnImpliedRate = state.lastLnImpliedRate; // Note: Actual balance of BaseLpt may be greater than `totalBaseLpt` because of rounding error. totalBaseLpt = (state.totalBaseLptTimesN * WAD / (N_COINS * state.virtualPrice)).toUint128(); totalUnderlying = state.totalUnderlying18.from18Decimals(uDecimals).toUint128(); emit UpdateLnImpliedRate(state.lastLnImpliedRate); } /// @notice credit: UniswapV3Pool /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize /// check function _balance(IERC20 token) internal view returns (uint256) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(IERC20.balanceOf.selector, address(this))); require(success && data.length >= 32); return abi.decode(data, (uint256)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` 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 amount) external returns (bool); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {IERC5095} from "./IERC5095.sol"; /// @notice Tranche interface /// @dev Tranche divides a yield-bearing token into two tokens: Principal and Yield tokens /// Unspecific types: Simply avoiding dependencies on other interfaces from our interfaces interface ITranche is IERC5095 { /* ==================== ERRORS ===================== */ error TimestampBeforeMaturity(); error TimestampAfterMaturity(); error ProtectedToken(); error Unauthorized(); error OnlyYT(); error ReentrancyGuarded(); error ZeroAddress(); error NoAccruedYield(); /* ==================== EVENTS ===================== */ /// @param adapter the address of the adapter /// @param maturity timestamp of maturity (seconds since Unix epoch) /// @param issuanceFee fee for issuing PT and YT event SeriesCreated(address indexed adapter, uint256 indexed maturity, uint256 issuanceFee); /// @param from the sender of the underlying token /// @param to the recipient of the PT and YT /// @param underlyingUsed the amount of underlying token used to issue PT and YT /// @param sharesUsed the amount of target token used to issue PT and YT (before deducting issuance fee) event Issue(address indexed from, address indexed to, uint256 underlyingUsed, uint256 sharesUsed); /// @param owner the address of the owner of the PT and YT (address that called collect()) /// @param shares the amount of Target token collected event Collect(address indexed owner, uint256 shares); /// @param owner the address of the owner of the PT and YT /// @param to the recipient of the underlying token redeemed /// @param underlyingRedeemed the amount of underlying token redeemed event RedeemWithYT(address indexed owner, address indexed to, uint256 underlyingRedeemed); /* ==================== STRUCTS ===================== */ /// @notice Series is a struct that contains all the information about a series. /// @param underlying the address of the underlying token /// @param target the address of the target token /// @param yt the address of the Yield Token /// @param adapter the address of the adapter /// @param mscale scale value at maturity /// @param maxscale max scale value from this series' lifetime /// @param issuanceFee fee for issuing PT and YT /// @param maturity timestamp of maturity (seconds since Unix epoch) struct Series { address underlying; address target; address yt; address adapter; uint256 mscale; uint256 maxscale; uint64 issuanceFee; uint64 maturity; } /// @notice GlobalScales is a struct that contains scale values that are used in multiple functions throughout the Tranche contract. /// @param mscale scale value at maturity. before maturity and settlement, this value is 0. /// @param maxscale max scale value from this series' lifetime. struct GlobalScales { uint128 mscale; uint128 maxscale; } /* ================== MUTATIVE METHODS =================== */ /// @notice deposit an `underlyingAmount` of underlying token into the yield source, receiving PT and YT. /// amount of PT and YT issued are the same. /// @param to the address to receive PT and YT /// @param underlyingAmount the amount of underlying token to deposit /// @return principalAmount the amount of PT and YT issued function issue(address to, uint256 underlyingAmount) external returns (uint256 principalAmount); /// @notice redeem an `principalAmount` of PT and YT for underlying token. /// @param from the address to burn PT and YT from /// @param to the address to receive underlying token /// @param pyAmount the amount of PT and YT to redeem /// @return underlyingAmount the amount of underlying token redeemed function redeemWithYT(address from, address to, uint256 pyAmount) external returns (uint256 underlyingAmount); /// @notice collect interest for `msg.sender` and transfer accrued interest to `msg.sender` /// NOTE: if the maturity has passed, all the YT balance of `msg.sender` is burned. /// @dev anyone can call this function to collect interest for themselves /// @return collected collected interest in Underlying token function collect() external returns (uint256 collected); /* ================== PERMISSIONED METHODS =================== */ /// @notice collect interest from the yield source and distribute it /// every YT transfer, this function is triggered by the Yield Token contract. /// only the Yield Token contract can call this function. /// NOTE: YT is not burned in this function even if the maturity has passed. /// @param from address to transfer the Yield Token from. i.e. the user who collects the interest. /// @param to address to transfer the Yield Token to (MUST NOT be zero address, CAN be the same as `from`) /// @param value amount of Yield Token transferred to `to` (CAN be 0) function updateUnclaimedYield(address from, address to, uint256 value) external; /* ================== VIEW METHODS =================== */ /// @notice get the address of Yield Token associated with this Tranche. function yieldToken() external view returns (address); /// @notice get Series struct function getSeries() external view returns (Series memory); /// @notice get an accrued yield that can be claimed by `account` (in unis of Target token) /// @dev this is reset to 0 when `account` claims the yield. /// @param account the address to check /// @return accruedInTarget function unclaimedYields(address account) external view returns (uint256 accruedInTarget); /// @notice get an accrued yield that can be claimed by `account` (in unis of Underlying token) /// @param account the address to check /// @return accruedInUnderlying accrued yield in underlying token function previewCollect(address account) external view returns (uint256 accruedInUnderlying); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // https://github.com/curvefi/tricrypto-ng/blob/0bc1191b6097c8854e4f09e385f6c2c79a5bb773/contracts/main/CurveTricryptoOptimizedWETH.vy import {IERC20} from "@openzeppelin/[email protected]/token/ERC20/IERC20.sol"; interface CurveTricryptoOptimizedWETH is IERC20 { /// @notice Exchange using wrapped native token by default /// @param i Index value for the input coin /// @param j Index value for the output coin /// @param dx Amount of input coin being swapped in /// @param min_dy Minimum amount of output coin to receive /// @param use_eth True if the input coin is native token, False otherwise /// @param receiver Address to send the output coin to. Default is msg.sender /// @return uint256 Amount of tokens at index j received by the `receiver function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy, bool use_eth, address receiver) external payable returns (uint256); /// @notice Exchange with callback method. /// @dev This method does not allow swapping in native token, but does allow /// swaps that transfer out native token from the pool. /// @dev Does not allow flashloans /// @dev One use-case is to reduce the number of redundant ERC20 token /// transfers in zaps. /// @param i Index value for the input coin /// @param j Index value for the output coin /// @param dx Amount of input coin being swapped in /// @param min_dy Minimum amount of output coin to receive /// @param use_eth True if output is native token, False otherwise /// @param sender Address to transfer input coin from /// @param receiver Address to send the output coin to /// @param cb Callback signature /// @return uint256 Amount of tokens at index j received by the `receiver` function exchange_extended( uint256 i, uint256 j, uint256 dx, uint256 min_dy, bool use_eth, address sender, address receiver, bytes32 cb ) external returns (uint256); /// @notice Adds liquidity into the pool. /// @param amounts Amounts of each coin to add. /// @param min_mint_amount Minimum amount of LP to mint. function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external payable returns (uint256); /// @notice Adds liquidity into the pool. /// @param amounts Amounts of each coin to add. /// @param min_mint_amount Minimum amount of LP to mint. /// @return uint256 Amount of LP tokens received by the `receiver /// @param use_eth True if native token is being added to the pool. /// @param receiver Address to send the LP tokens to. Default is msg.sender function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount, bool use_eth, address receiver) external payable returns (uint256); /// @notice This withdrawal method is very safe, does no complex math since /// tokens are withdrawn in balanced proportions. No fees are charged. /// @param amount Amount of LP tokens to burn /// @param min_amounts Minimum amounts of tokens to withdraw /// @param use_eth Whether to withdraw ETH or not /// @param receiver Address to send the withdrawn tokens to /// @param claim_admin_fees If True, call self._claim_admin_fees(). Default is True. /// @return uint256[3] Amount of pool tokens received by the `receiver` function remove_liquidity( uint256 amount, uint256[3] calldata min_amounts, bool use_eth, address receiver, bool claim_admin_fees ) external returns (uint256[3] memory); /// @notice Withdraw liquidity in a single token. /// Involves fees (lower than swap fees). /// @dev This operation also involves an admin fee claim. /// @param token_amount Amount of LP tokens to burn /// @param i Index of the token to withdraw /// @param min_amount Minimum amount of token to withdraw. /// @param use_eth Whether to withdraw ETH or not /// @param receiver Address to send the withdrawn tokens to /// @return Amount of tokens at index i received by the `receiver` function remove_liquidity_one_coin( uint256 token_amount, uint256 i, uint256 min_amount, bool use_eth, address receiver ) external returns (uint256); /////////////////////////////////////////////////////////// // View methods /////////////////////////////////////////////////////////// /// @notice Returns the balance of the coin at index `i` function balances(uint256 i) external view returns (uint256); /// @notice Calculate LP tokens minted or to be burned for depositing or /// removing `amounts` of coins /// @dev Includes fee. /// @param amounts Amounts of tokens being deposited or withdrawn /// @param deposit True if it is a deposit action, False if withdrawn. /// @return uint256 Amount of LP tokens deposited or withdrawn. function calc_token_amount(uint256[3] calldata amounts, bool deposit) external view returns (uint256); function get_dy(uint256 i, uint256 j, uint256 dx) external view returns (uint256); function get_dx(uint256 i, uint256 j, uint256 dy) external view returns (uint256); /// @notice Calculates the current price of the LP token with respect to the coin at the 0th index /// @dev This function should be implemented to return the LP price /// @return The current LP price as a uint256 function lp_price() external view returns (uint256); /// @notice calculate the current virtual price of the pool's LP token (in 18 decimals) /// @dev Non read-reenrant. /// @dev https://docs.curve.fi/cryptoswap-exchange/tricrypto-ng/pools/tricrypto/?h=virtual#get_virtual_price function get_virtual_price() external view returns (uint256); /// @notice Returns the oracle price of the coin at index `k` with respect to the coin at index 0 /// @dev The oracle is an exponential moving average, with a periodicity determined internally. /// The aggregated prices are cached state prices (dy/dx) calculated AFTER the latest trade. /// @param k The index of the coin for which the oracle price is needed (k = 0 or 1) /// @return The oracle price of the coin at index `k` as a uint256 function price_oracle(uint256 k) external view returns (uint256); /// @notice Calculates output tokens with fee /// @param token_amount LP Token amount to burn /// @param i token in which liquidity is withdrawn /// @return uint256 Amount of ith tokens received for burning token_amount LP tokens. function calc_withdraw_one_coin(uint256 token_amount, uint256 i) external view returns (uint256); function calc_token_fee(uint256[3] calldata amounts, uint256[3] calldata xp) external view returns (uint256); function fee_calc(uint256[3] calldata xp) external view returns (uint256); /// @notice Returns i-th coin address. /// @param i Index of the coin. i must be 0, 1 or 2. function coins(uint256 i) external view returns (address); /// @dev Returns the address of the factory that created the pool. /// @return address The factory address. function factory() external view returns (address); function D() external view returns (uint256); /// @dev Returns the cached virtual price of the pool. function virtual_price() external view returns (uint256); /// @dev Returns the current pool amplification parameter. /// @return uint256 The A parameter. function A() external view returns (uint256); /// @dev Returns the current pool gamma parameter. /// @return uint256 The gamma parameter. function gamma() external view returns (uint256); /////////////////////////////////////////////////////////// // Protected methods /////////////////////////////////////////////////////////// /// @notice Initialise Ramping A and gamma parameter values linearly. /// @dev Only accessible by factory admin, and only /// @param future_A The future A value. /// @param future_gamma The future gamma value. /// @param future_time The timestamp at which the ramping will end. function ramp_A_gamma(uint256 future_A, uint256 future_gamma, uint256 future_time) external; }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {IERC20} from "@openzeppelin/[email protected]/token/ERC20/IERC20.sol"; import {CurveTricryptoOptimizedWETH} from "./external/CurveTricryptoOptimizedWETH.sol"; import {PoolState} from "../libs/PoolMath.sol"; interface INapierPool { event Mint(address indexed receiver, uint256 liquidity, uint256 underlyingUsed, uint256 baseLptUsed); event Burn(address indexed receiver, uint256 liquidity, uint256 underlyingOut, uint256 baseLptOut); event Swap( address indexed caller, address indexed receiver, int256 netUnderlying, uint256 index, int256 netPt, uint256 swapFee, uint256 protocolFee ); event SwapBaseLpt( address indexed caller, address indexed receiver, int256 netUnderlying, int256 netBaseLpt, uint256 swapFee, uint256 protocolFee ); event UpdateLnImpliedRate(uint256 lnImpliedRate); /** * @notice Add liquidity to the pool with Underlying and base lp token. * Caller have to transfer tokens to this contract before calling this function. * @param underlyingInDesired The desired amount of underlying asset to add. * @param baseLptInDesired The desired amount of base lp token to add. * @param recipient The recipient of the liquidity tokens. * @param data Additional data for callback. * @return The amount of liquidity tokens received. */ function addLiquidity(uint256 underlyingInDesired, uint256 baseLptInDesired, address recipient, bytes memory data) external returns (uint256); /** * @notice Remove liquidity from the pool. * Caller have to transfer Lp token to this contract before calling this function. * @param recipient The recipient of the assets. * @return The amounts of base lp token and underlying asset received. */ function removeLiquidity(address recipient) external returns (uint256, uint256); /** * @notice Swap exact amount of PT for Underlying asset. * It supports flash swap by specifying the callback data. * Flash swap enables user to receive Underlying asset before paying PT. * If the pool contract received enough PT after the callback, the swap is successful. Otherwise, the swap is reverted. * @param index The index of the PT. * @param ptIn The amount of PT to swap. * @param recipient The recipient of the swapped underlying asset. * @param data Additional data for the flash swap. * @return The amount of underlying asset received. */ function swapPtForUnderlying(uint256 index, uint256 ptIn, address recipient, bytes calldata data) external returns (uint256); /** * @notice Swap Underlying asset for exact amount of PT. * It supports flash swap by specifying the callback data. * It enables user to receive PT before paying Underlying asset. * if the pool contract received enough Underlying asset after the callback, the swap is successful. Otherwise, the swap is reverted. * @param index The index of the PT. * @param ptOut The desired amount of PT to receive. * @param recipient The recipient of the PT. * @param data Additional data for the flash swap. * @return The amount of PT received. */ function swapUnderlyingForPt(uint256 index, uint256 ptOut, address recipient, bytes calldata data) external returns (uint256); /** * @notice Swap Underlying asset for exact amount of Base LP token. * @param baseLpOut The desired amount of Base LP token to receive. * @param recipient The recipient of the Base LP token. */ function swapUnderlyingForExactBaseLpToken(uint256 baseLpOut, address recipient) external returns (uint256); /** * @notice Swap exact amount of Base LP token for Underlying asset. * @param recipient The recipient of the Underlying asset. */ function swapExactBaseLpTokenForUnderlying(uint256 baseLptIn, address recipient) external returns (uint256); /** * @notice Maturity of the pool, in unix timestamp. * @dev Maturity is same as the maturity of Principal Token in the pool. */ function maturity() external view returns (uint256); function totalUnderlying() external view returns (uint128); function totalBaseLpt() external view returns (uint128); function getAssets() external view returns (address, address); /** * @notice State of the pool. * @dev This function is not expected to be called on-chain. */ function readState() external view returns (PoolState memory); function tricrypto() external view returns (CurveTricryptoOptimizedWETH); function principalTokens() external view returns (IERC20[3] memory); function lastLnImpliedRate() external view returns (uint256); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface INapierSwapCallback { /** * @notice Callback function to handle the token swap. * @param underlyingDelta The change in underlying after the swap. * @param ptDelta The change in Principal token after the swap. * @param data Additional data passed to the callback. Can be used to pass context-specific information. */ function swapCallback(int256 underlyingDelta, int256 ptDelta, bytes calldata data) external; }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface INapierMintCallback { /** * @notice Callback function to handle the add liquidity. * @param underlyingDelta The change in underlying. * @param baseLptDelta The change in Base pool LP token. * @param data Additional data passed to the callback. Can be used to pass context-specific information. */ function mintCallback(uint256 underlyingDelta, uint256 baseLptDelta, bytes calldata data) external; }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPoolFactory { event Deployed(address indexed basePool, address indexed underlying, address indexed pool); event AuthorizedCallbackReceiver(address indexed callback); event RevokedCallbackReceiver(address indexed callback); struct PoolAssets { address basePool; address underlying; address[3] principalTokens; } struct PoolConfig { int256 initialAnchor; uint256 scalarRoot; uint80 lnFeeRateRoot; uint8 protocolFeePercent; address feeRecipient; } struct InitArgs { PoolAssets assets; PoolConfig configs; } /// @notice Deploy a new NapierPool contract. /// @dev Only the factory owner can call this function. /// @param basePool Base pool contract /// @param underlying underlying asset function deploy(address basePool, address underlying, PoolConfig calldata poolConfig) external returns (address); /// @notice Authorize swap callback /// @dev Only the factory owner can call this function. /// @param callback Callback receiver function authorizeCallbackReceiver(address callback) external; /// @notice Revoke swap callback authorization /// @dev Only the factory owner can call this function. /// @param callback Callback receiver function revokeCallbackReceiver(address callback) external; function isCallbackReceiverAuthorized(address callback) external view returns (bool); /// @notice calculate the address of a tranche with CREATE2 using the adapter and maturity as salt function poolFor(address basePool, address underlying) external view returns (address); /// @param pool a pool address /// @dev returns the pool parameters used to deploy the pool /// this function doesn't revert even if the pool doesn't exist. It returns the default values in that case. /// @return the pool parameters function getPoolAssets(address pool) external view returns (PoolAssets memory); /// @notice Owner of this contract function owner() external view returns (address); function args() external view returns (InitArgs memory); function POOL_CREATION_HASH() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @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 * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits"); 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 * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits"); 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 * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits"); 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 * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); 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 * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits"); 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 * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); 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 * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits"); 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 * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits"); 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 * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits"); 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 * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits"); 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 * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits"); 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 * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits"); 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 * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits"); 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 * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits"); 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 * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits"); 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 * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); 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 * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits"); 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 * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); 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 * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); 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 * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); 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 * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); 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 * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits"); 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 * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits"); 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 * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); 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 * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits"); 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 * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits"); 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 * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits"); 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 * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); 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 * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits"); 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 * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); 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 * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); 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 * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); require(downcasted == value, "SafeCast: value doesn't fit in 248 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); require(downcasted == value, "SafeCast: value doesn't fit in 240 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); require(downcasted == value, "SafeCast: value doesn't fit in 224 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); require(downcasted == value, "SafeCast: value doesn't fit in 216 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); require(downcasted == value, "SafeCast: value doesn't fit in 208 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); require(downcasted == value, "SafeCast: value doesn't fit in 200 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); require(downcasted == value, "SafeCast: value doesn't fit in 192 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); require(downcasted == value, "SafeCast: value doesn't fit in 184 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); require(downcasted == value, "SafeCast: value doesn't fit in 176 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); require(downcasted == value, "SafeCast: value doesn't fit in 168 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); require(downcasted == value, "SafeCast: value doesn't fit in 160 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); require(downcasted == value, "SafeCast: value doesn't fit in 152 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); require(downcasted == value, "SafeCast: value doesn't fit in 144 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); require(downcasted == value, "SafeCast: value doesn't fit in 136 bits"); } /** * @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 * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); require(downcasted == value, "SafeCast: value doesn't fit in 128 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); require(downcasted == value, "SafeCast: value doesn't fit in 120 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); require(downcasted == value, "SafeCast: value doesn't fit in 112 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); require(downcasted == value, "SafeCast: value doesn't fit in 88 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); require(downcasted == value, "SafeCast: value doesn't fit in 72 bits"); } /** * @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 * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); require(downcasted == value, "SafeCast: value doesn't fit in 64 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); require(downcasted == value, "SafeCast: value doesn't fit in 48 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); require(downcasted == value, "SafeCast: value doesn't fit in 40 bits"); } /** * @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 * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); require(downcasted == value, "SafeCast: value doesn't fit in 32 bits"); } /** * @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 * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); } /** * @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 * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); require(downcasted == value, "SafeCast: value doesn't fit in 16 bits"); } /** * @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 * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); require(downcasted == value, "SafeCast: value doesn't fit in 8 bits"); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); } /** * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } } /** * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. * Revert on invalid signature. */ function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { 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) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv 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. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.19; /// @notice This library contains the math used in NapierPool. /// @dev Taken and modified from Pendle V2: https://github.com/pendle-finance/pendle-core-v2-public/blob/163783b09014e515b645b83936fec32c5731d092/contracts/core/Market/MarketMathCore.sol /// @dev Taken and modified from Notional : https://github.com/notional-finance/contracts-v2/blob/1845605ab0d9eec9b5dd374cf7c246957b534f85/contracts/internal/markets/Market.sol /// @dev Naming convention: /// - `pt` => baseLpt: BasePool LP token /// - `asset` => `underlying`: underlying asset /// - `totalPt` => `totalBaseLptTimesN`: total BasePool LP token reserve in the pool multiplied by 3 * virtual_price where virtual_price is the share price of the Tricrypto LP token /// See NapierPool.sol for more details. /// - `totalAsset` => `totalUnderlying`: total underlying asset reserve in the pool /// - `executeTradeCore` function => `executeSwap` function /// - `calculateTrade` function => `calculateSwap` function /// - `getMarketPreCompute` function => `computeAmmParameters` function /// - `setNewMarketStateTrade` function => `_setPostPoolState` function /// @dev All functions in this library are view functions. /// @dev Changes: /// 1) Math library dependency from LogExpMath to PRBMath etc. /// 2) Swap functions multiply the parameter `exactPtToAccount` by N(=3) to make it equivalent to the amount of PT being swapped. /// 3) Swap functions divide the computed underlying swap result by N. /// 3) Remove some redundant checks (e.g. check for maturity) /// 4) Remove some redundant variables (e.g. `totalAsset` in `MarketPreCompute`) /// 5) Remove some redundant functions (`addLiquidity` and `removeLiquidity`) // libraries import {Math} from "@openzeppelin/[email protected]/utils/math/Math.sol"; import {SafeCast} from "@openzeppelin/[email protected]/utils/math/SafeCast.sol"; import {FixedPointMathLib} from "@napier/v1-tranche/src/utils/FixedPointMathLib.sol"; import {SignedMath} from "./SignedMath.sol"; import {sd, ln, intoInt256} from "@prb/math/SD59x18.sol"; // used for logarithm operation import {ud, exp, intoUint256} from "@prb/math/UD60x18.sol"; // used for exp operation import {Errors} from "./Errors.sol"; /// @param totalBaseLptTimesN - Reserve Curve v2 Tricrypto 3PrincipalToken Pool LP token x times N(=# of Curve v2 Pool assets) in 18 decimals /// @param totalUnderlying18 - Reserve underlying asset in 18 decimals /// @param scalarRoot - Scalar root for NapierPool (See whitepaper) /// @param maturity - Expiry of NapierPool (Unix timestamp) /// @param lnFeeRateRoot - Logarithmic fee rate root /// @param protocolFeePercent - Protocol fee percent (base 100) /// @param lastLnImpliedRate - Last ln implied rate struct PoolState { uint256 totalBaseLptTimesN; uint256 totalUnderlying18; // Tricrypto pool LP token virtual price uint256 virtualPrice; /// immutable variables /// uint256 scalarRoot; uint256 maturity; /// fee data /// uint256 lnFeeRateRoot; uint256 protocolFeePercent; // 100=100% /// last trade data /// uint256 lastLnImpliedRate; } /// @notice Variables that are used to compute the swap result /// @dev params that are expensive to compute, therefore we pre-compute them struct PoolPreCompute { int256 rateScalar; int256 rateAnchor; int256 feeRate; } /// @title PoolMath - library for calculating swaps /// @notice Taken and modified from Pendle V2: https://github.com/pendle-finance/pendle-core-v2-public/blob/163783b09014e515b645b83936fec32c5731d092/contracts/core/Market/MarketMathCore.sol /// @dev Swaps take place between the BasePool LP token and the underlying asset. /// The BasePool LP token is basket of 3 principal tokens. /// @dev The AMM formula is defined in terms of the amount of PT being swapped. /// @dev The math assumes two tokens (pt and underlying) have same decimals. Need to convert if they have different decimals. /// @dev All functions in this library are view functions. library PoolMath { /// @notice Minimum liquidity in the pool uint256 internal constant MINIMUM_LIQUIDITY = 10 ** 3; /// @notice Percentage base (100=100%) int256 internal constant FULL_PERCENTAGE = 100; /// @notice Day in seconds in Unix timestamp uint256 internal constant DAY = 86400; /// @notice Year in seconds in Unix timestamp uint256 internal constant IMPLIED_RATE_TIME = 365 * DAY; /// @notice Max proportion of BasePool LP token / (BasePool LP token + underlying asset) in the pool uint256 internal constant MAX_POOL_PROPORTION = 0.96 * 1e18; // 96% int256 internal constant N_COINS = 3; using FixedPointMathLib for uint256; using SignedMath for int256; using SignedMath for uint256; using SafeCast for uint256; using SafeCast for int256; /// @param pool State - pool state of the pool /// @param exactBaseLptIn - exact amount of Base Pool LP tokens to be swapped in /// @return underlyingOut18 - underlying tokens to be swapped out (18 decimals) /// @return swapFee18 - swap fee in underlying (18 decimals) /// @return protocolFee18 - protocol fee in underlying (18 decimals) function swapExactBaseLpTokenForUnderlying(PoolState memory pool, uint256 exactBaseLptIn) internal view returns (uint256 underlyingOut18, uint256 swapFee18, uint256 protocolFee18) { (int256 _netUnderlyingToAccount18, int256 _netUnderlyingFee18, int256 _netUnderlyingToProtocol18) = executeSwap( pool, // Note: sign is defined from the perspective of the swapper. // negative because the swapper is selling pt // Note: Here we are multiplying by virtualPrice * N_COINS because the swap formula is defined in terms of the amount of PT being swapped. // Basically BaseLpt is equivalent to more than 3 times the amount of PT due to the initial deposit of 1:1:1:1=pt1:pt2:pt3:Lp share in Curve pool. // The LP token accrues trade fees on the Tricrypto pool and the virtual price’s value would increase over time. FixedPointMathLib.mulWadDown(exactBaseLptIn, pool.virtualPrice * uint256(N_COINS)).neg() // user would get smaller amount of underlying due to the rounding down ); underlyingOut18 = _netUnderlyingToAccount18.toUint256(); swapFee18 = _netUnderlyingFee18.toUint256(); protocolFee18 = _netUnderlyingToProtocol18.toUint256(); } /// @param pool State - pool state of the pool /// @param exactBaseLptOut exact amount of Base Pool LP tokens to be swapped out /// @return underlyingIn18 - underlying tokens to be swapped in (18 decimals) /// @return swapFee18 - swap fee in underlying (18 decimals) /// @return protocolFee18 - protocol fee in underlying (18 decimals) function swapUnderlyingForExactBaseLpToken(PoolState memory pool, uint256 exactBaseLptOut) internal view returns (uint256 underlyingIn18, uint256 swapFee18, uint256 protocolFee18) { (int256 _netUnderlyingToAccount18, int256 _netUnderlyingFee18, int256 _netUnderlyingToProtocol18) = executeSwap( pool, // Note: sign is defined from the perspective of the swapper. // positive because the swapper is buying pt FixedPointMathLib.mulWadUp(exactBaseLptOut, pool.virtualPrice * uint256(N_COINS)).toInt256() // user would need to pay more underlying due to the rounding up ); underlyingIn18 = _netUnderlyingToAccount18.neg().toUint256(); swapFee18 = _netUnderlyingFee18.toUint256(); protocolFee18 = _netUnderlyingToProtocol18.toUint256(); } /// @notice Compute swap result given the amount of base pool LP tokens to be swapped in. /// @dev This function is used to compute the swap result before the swap is executed. /// @param pool State - pool state of the pool /// @param netBaseLptToAccount (int256) amount of base pool LP tokens to be swapped in (negative if selling pt) multiplied by the number of BasePool assets /// Note: sign is defined from the perspective of the swapper. positive if the swapper is buying pt. /// @return netUnderlyingToAccount18 (int256) amount of underlying tokens to be swapped out /// @return netUnderlyingFee18 (int256) total fee. including protocol fee. /// `netUnderlyingFee18 - netUnderlyingToProtocol` will be distributed to LP holders. /// @return netUnderlyingToProtocol18 (int256) Protocol fee function executeSwap(PoolState memory pool, int256 netBaseLptToAccount) internal view returns (int256 netUnderlyingToAccount18, int256 netUnderlyingFee18, int256 netUnderlyingToProtocol18) { if (pool.totalBaseLptTimesN.toInt256() <= netBaseLptToAccount) { revert Errors.PoolInsufficientBaseLptForTrade(); } /// ------------------------------------------------------------ /// MATH /// ------------------------------------------------------------ PoolPreCompute memory comp = computeAmmParameters(pool); (netUnderlyingToAccount18, netUnderlyingFee18, netUnderlyingToProtocol18) = calculateSwap(pool, comp, netBaseLptToAccount); /// ------------------------------------------------------------ /// WRITE /// ------------------------------------------------------------ _setPostPoolState(pool, comp, netBaseLptToAccount, netUnderlyingToAccount18, netUnderlyingToProtocol18); } /// @notice Compute the pseudo invariant of the pool. /// @dev The pseudo invariant is computed every swap before the swap is executed. /// @param pool State - pool state of the pool function computeAmmParameters(PoolState memory pool) internal view returns (PoolPreCompute memory cache) { uint256 timeToExpiry = pool.maturity - block.timestamp; cache.rateScalar = _getRateScalar(pool, timeToExpiry); cache.rateAnchor = _getRateAnchor( pool.totalBaseLptTimesN, pool.lastLnImpliedRate, pool.totalUnderlying18, cache.rateScalar, timeToExpiry ); cache.feeRate = _getExchangeRateFromImpliedRate(pool.lnFeeRateRoot, timeToExpiry); } /// @notice Calculate the new `RateAnchor(t)` based on the pre-trade implied rate, `lastImpliedRate`, before the swap. /// To ensure interest rate continuity, we adjust the `rateAnchor(t)` such that the pre-trade implied rate at t* remains the same as `lastImpliedRate`. /// /// Formulas for `rateAnchor(t)`: /// ---------------------------- /// yearsToExpiry(t) = timeToExpiry / 365 days /// /// portion(t*) = totalBaseLptTimesN / (totalBaseLptTimesN + totalUnderlying18) /// /// extRate(t*) = lastImpliedRate^(yearsToExpiry(t)) /// = e^(ln(lastImpliedRate) * yearsToExpiry(t)) /// /// rateAnchor(t) = extRate(t*) - ln(portion(t*)) / rateScalar(t) /// ---------------------------- /// Where `portion(t*)` represents the portion of the pool that is BasePool LP token at t* and `extRate(t*)` is the exchange rate at t*. /// /// @param totalBaseLptTimesN total Base Lp token in the pool /// @param lastLnImpliedRate the implied rate for the last trade that occurred at t_last. /// @param totalUnderlying18 total underlying in the pool /// @param rateScalar a parameter of swap formula. Calculated as `scalarRoot` divided by `yearsToExpiry` /// @param timeToExpiry time to maturity in seconds /// @return rateAnchor the new rate anchor function _getRateAnchor( uint256 totalBaseLptTimesN, uint256 lastLnImpliedRate, uint256 totalUnderlying18, int256 rateScalar, uint256 timeToExpiry ) internal pure returns (int256 rateAnchor) { // `extRate(t*) = e^(lastLnImpliedRate * yearsToExpiry(t))` // Get pre-trade exchange rate with zero-fee int256 preTradeExchangeRate = _getExchangeRateFromImpliedRate(lastLnImpliedRate, timeToExpiry); // exchangeRate should not be below 1. // But it is mathematically almost impossible to happen because `exp(x) < 1` is satisfied for all `x < 0`. // Here x = lastLnImpliedRate * yearsToExpiry(t), which is very unlikely to be negative.(or // more accurately the natural log rounds down to zero). `lastLnImpliedRate` is guaranteed to be positive when it is set // and `yearsToExpiry(t)` is guaranteed to be positive because swap can only happen before maturity. // We still check for this case to be safe. require(preTradeExchangeRate >= SignedMath.WAD); uint256 proportion = totalBaseLptTimesN.divWadDown(totalBaseLptTimesN + totalUnderlying18); int256 lnProportion = _logProportion(proportion); // Compute `rateAnchor(t) = extRate(t*) - ln(portion(t*)) / rateScalar(t)` rateAnchor = preTradeExchangeRate - lnProportion.divWadDown(rateScalar); } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// @dev Formula: `E = e^rt` /// @return exchangeRate the price of underlying token in Base LP token. Guaranteed to be positive or zero. function _getExchangeRateFromImpliedRate(uint256 lnImpliedRate, uint256 timeToExpiry) internal pure returns (int256 exchangeRate) { uint256 rt = (lnImpliedRate * timeToExpiry) / IMPLIED_RATE_TIME; exchangeRate = exp(ud(rt)).intoUint256().toInt256(); } /// @notice Compute swap result given the delta of baseLpt an swapper wants to swap. /// @param pool State - pool state of the pool /// @param comp PreCompute - pre-computed values of the pool /// @param netBaseLptToAccount the delta of baseLpt the swapper wants to swap. /// @dev Note: Ensure that abs(`netBaseLptToAccount`) is not greater than `totalBaseLptTimesN`. /// @return netUnderlyingToAccount18 the amount of underlying the swapper will receive /// negative if the swapper is selling BaseLpt and positive if the swapper is buying BaseLpt. /// @return underlyingFee18 the amount of underlying charged as swap fee /// this includes `underlyingToProtocol18` /// @return underlyingToProtocol18 the amount of underlying the Pool fee recipient will receive as fee /// Protocol accrues fee in underlying. function calculateSwap( PoolState memory pool, PoolPreCompute memory comp, int256 netBaseLptToAccount // d_pt ) internal pure returns (int256, int256, int256) { // Calculates the exchange rate from underlying to baseLpt before any fees are applied // Note: The exchange rate is int type but it must be always strictly gt 1. // Note: `netBaseLptToAccount` should be checked prior to calling this function int256 preFeeExchangeRate = _getExchangeRate( pool.totalBaseLptTimesN, pool.totalUnderlying18, comp.rateScalar, comp.rateAnchor, netBaseLptToAccount ).toInt256(); // Basically swap formula is: // netBaseLptToAccount // netUnderlyingToAccount18 = -1 * ──────────────────────── // extRate // where `netBaseLptToAccount` is the delta of baseLpt (`d_pt`) and `netUnderlyingToAccount18` is the delta of underlying (`d_u`). // because if `d_pt > 0`, then `d_u < 0` and vice versa. // fees can be applied to the `extRate`. // `postFeeExchangeRate = preFeeExchangeRate / feeRate` if `netBaseLptToAccount > 0` else `postFeeExchangeRate = preFeeExchangeRate * feeRate` int256 netUnderlying18 = netBaseLptToAccount.divWadDown(preFeeExchangeRate).neg(); // See whitepaper for the formula: // fee is calculated as the difference between the underlying amount before and after the fee is applied: // fee = underlyingNoFee - underlyingWithFee // where `underlyingNoFee = - (ptToAccount / preFeeExchangeRate)` // and `underlyingWithFee = - (ptToAccount / postFeeExchangeRate)` // // Therefore: // fee = - (ptToAccount / preFeeExchangeRate) + (ptToAccount / postFeeExchangeRate) int256 underlyingFee18; if (netBaseLptToAccount > 0) { // User swap underlying for baseLpt // Exchange rate after fee is applied is: // `postFeeExchangeRate := preFeeExchangeRate / feeRate` // `postFeeExchangeRate` must be strictly gt 1. // It's possible that the fee pushes the implied rate into negative territory. This is not allowed. int256 postFeeExchangeRate = preFeeExchangeRate.divWadDown(comp.feeRate); if (postFeeExchangeRate < SignedMath.WAD) revert Errors.PoolExchangeRateBelowOne(postFeeExchangeRate); // fee = - (ptToAccount / preFeeExchangeRate) + (ptToAccount / postFeeExchangeRate) // = (ptToAccount / preFeeExchangeRate) * (feeRate - 1) // = netUnderlying18 * (feeRate - 1) underlyingFee18 = netUnderlying18.mulWadDown(SignedMath.WAD - comp.feeRate); } else { // User swap baseLpt for underlying // Exchange rate after fee is applied is: // `postFeeExchangeRate := preFeeExchangeRate * feeRate` // In this case, `postFeeExchangeRate` can't be below 1 unlike the case above. // fee = - (ptToAccount / preFeeExchangeRate) + (ptToAccount / postFeeExchangeRate) // = - (ptToAccount / preFeeExchangeRate) + (ptToAccount / (preFeeExchangeRate * feeRate)) // = - (ptToAccount / preFeeExchangeRate) * (1 - 1 / feeRate) // = - (ptToAccount / preFeeExchangeRate) * (feeRate - 1) / feeRate // Note: ptToAccount is negative in this branch so we negate it to ensure that fee is a positive number underlyingFee18 = ((netUnderlying18 * (SignedMath.WAD - comp.feeRate)) / comp.feeRate).neg(); } // Subtract swap fee // underlyingWithFee = underlyingNoFee - fee int256 netUnderlyingToAccount18 = netUnderlying18 - underlyingFee18; // Charge protocol fee on swap fee // This underlying will be removed from the pool reserve int256 underlyingToProtocol18 = (underlyingFee18 * pool.protocolFeePercent.toInt256()) / FULL_PERCENTAGE; return (netUnderlyingToAccount18, underlyingFee18, underlyingToProtocol18); } /// @notice Update pool state cache after swap is executed /// @param pool pool state of the pool /// @param comp swap formula pre-computed values /// @param netBaseLptToAccount net Base Lpt to account. negative if the swapper is selling BaseLpt /// @param netUnderlyingToAccount18 net underlying to account. positive if the swapper is selling BaseLpt. /// @param netUnderlyingToProtocol18 should be removed from the pool reserve `totalUnderlying18`. must be positive function _setPostPoolState( PoolState memory pool, PoolPreCompute memory comp, int256 netBaseLptToAccount, int256 netUnderlyingToAccount18, int256 netUnderlyingToProtocol18 ) internal view { // update pool state // Note safe because pre-trade check ensures totalBaseLptTimesN >= netBaseLptToAccount pool.totalBaseLptTimesN = (pool.totalBaseLptTimesN.toInt256() - netBaseLptToAccount).toUint256(); pool.totalUnderlying18 = (pool.totalUnderlying18).toInt256().subNoNeg( netUnderlyingToAccount18 + netUnderlyingToProtocol18 ).toUint256(); // compute post-trade implied rate // this will be used to compute the new rateAnchor for the next trade uint256 timeToExpiry = pool.maturity - block.timestamp; pool.lastLnImpliedRate = _getLnImpliedRate( pool.totalBaseLptTimesN, pool.totalUnderlying18, comp.rateScalar, comp.rateAnchor, timeToExpiry ); // It's technically unlikely that the implied rate is actually exactly zero but we will still fail // in this case. if (pool.lastLnImpliedRate == 0) revert Errors.PoolZeroLnImpliedRate(); } /// @notice Get rate scalar given the pool state and time to maturity. /// @dev Formula: `scalarRoot * ONE_YEAR / yearsToExpiry` function _getRateScalar(PoolState memory pool, uint256 timeToExpiry) internal pure returns (int256) { uint256 rateScalar = (pool.scalarRoot * IMPLIED_RATE_TIME) / timeToExpiry; if (rateScalar == 0) revert Errors.PoolRateScalarZero(); return rateScalar.toInt256(); } /// @notice Calculates the current pool implied rate. /// ln(extRate) * ONE_YEAR / timeToExpiry /// @return lnImpliedRate the implied rate function _getLnImpliedRate( uint256 totalBaseLptTimesN, uint256 totalUnderlying18, int256 rateScalar, int256 rateAnchor, uint256 timeToExpiry ) internal pure returns (uint256 lnImpliedRate) { // This should ensure that exchange rate < FixedPointMathLib.WAD int256 exchangeRate = _getExchangeRate(totalBaseLptTimesN, totalUnderlying18, rateScalar, rateAnchor, 0).toInt256(); // exchangeRate >= 1 so its ln(extRate) >= 0 int256 lnRate = ln(sd(exchangeRate)).intoInt256(); lnImpliedRate = (uint256(lnRate) * IMPLIED_RATE_TIME) / timeToExpiry; } /// @notice Calculates exchange rate given the total baseLpt and total underlying. /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalPt / (totalPt + totalUnderlying) /// /// @dev Revert if the exchange rate is below 1. Prevent users from swapping when 1 baseLpt is worth more than 1 underlying. /// @dev Revert if the proportion of baseLpt to total is greater than MAX_POOL_PROPORTION. /// @param totalBaseLptTimesN the total baseLpt in the pool /// @param totalUnderlying18 the total underlying in the pool /// @param rateScalar the scalar used to compute the exchange rate /// @param rateAnchor the anchor used to compute the exchange rate /// @param netBaseLptToAccount the net baseLpt to the account (negative if account is swapping baseLpt for underlying) /// @return exchangeRate the price of underlying token in terms of Base LP token function _getExchangeRate( uint256 totalBaseLptTimesN, uint256 totalUnderlying18, int256 rateScalar, int256 rateAnchor, int256 netBaseLptToAccount ) internal pure returns (uint256) { // Revert if there is not enough baseLpt to support this swap. // Note: Ensure that abs(`netBaseLptToAccount`) is not greater than `totalBaseLptTimesN` before calling this function uint256 numerator = (totalBaseLptTimesN.toInt256() - netBaseLptToAccount).toUint256(); uint256 proportion = numerator.divWadDown(totalBaseLptTimesN + totalUnderlying18); if (proportion > MAX_POOL_PROPORTION) { revert Errors.PoolProportionTooHigh(); } int256 lnProportion = _logProportion(proportion); int256 exchangeRate = lnProportion.divWadDown(rateScalar) + rateAnchor; if (exchangeRate < int256(FixedPointMathLib.WAD)) revert Errors.PoolExchangeRateBelowOne(exchangeRate); return exchangeRate.toUint256(); } /// @notice Compute Logit function (log(p/(1-p)) given a proportion `p`. /// @param proportion the proportion of baseLpt to (baseLpt + underlying) (0 <= proportion <= 1e18) function _logProportion(uint256 proportion) internal pure returns (int256 logitP) { if (proportion == FixedPointMathLib.WAD) revert Errors.PoolProportionMustNotEqualOne(); // input = p/(1-p) int256 input = proportion.divWadDown(FixedPointMathLib.WAD - proportion).toInt256(); // logit(p) = log(input) = ln(p/(1-p)) logitP = ln(sd(input)).intoInt256(); } /// @notice Compute the initial implied rate of the pool. /// @dev This function is expected to be called only once when initial liquidity is added. /// @param pool pool state of the pool /// @param initialAnchor initial anchor of the pool /// @return initialLnImpliedRate the initial implied rate function computeInitialLnImpliedRate(PoolState memory pool, int256 initialAnchor) internal view returns (uint256) { uint256 timeToExpiry = pool.maturity - block.timestamp; int256 rateScalar = _getRateScalar(pool, timeToExpiry); return _getLnImpliedRate(pool.totalBaseLptTimesN, pool.totalUnderlying18, rateScalar, initialAnchor, timeToExpiry); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.19; import {SafeCast} from "@openzeppelin/[email protected]/utils/math/SafeCast.sol"; library SignedMath { int256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulDivDown(int256 x, int256 y, int256 z) internal pure returns (int256) { int256 xy = x * y; unchecked { return xy / z; } } function subNoNeg(int256 a, int256 b) internal pure returns (int256) { require(a >= b, "negative"); return a - b; // no unchecked since if b is very negative, a - b might overflow } function mulWadDown(int256 a, int256 b) internal pure returns (int256) { return mulDivDown(a, b, WAD); } function divWadDown(int256 a, int256 b) internal pure returns (int256) { return mulDivDown(a, WAD, b); } function neg(int256 x) internal pure returns (int256) { return x * (-1); } function neg(uint256 x) internal pure returns (int256) { return SafeCast.toInt256(x) * (-1); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library DecimalConversion { /// @dev Turns a token into 18 point decimal /// @param amount The amount of the token in native decimal encoding /// @param decimals The token decimals (MUST be less than 18) /// @return The amount of token encoded into 18 point fixed point function to18Decimals(uint256 amount, uint8 decimals) internal pure returns (uint256) { // we shift left by the difference return amount * 10 ** (18 - decimals); } /// @dev Turns an 18 fixed point amount into a token amount /// @param amount The amount of the token in 18 decimal fixed point /// @param decimals The token decimals (MUST be less than 18) /// @return The amount of token encoded in native decimal point function from18Decimals(uint256 amount, uint8 decimals) internal pure returns (uint256) { // we shift right the amount by the number of decimals return amount / 10 ** (18 - decimals); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.19; ///////////////////////////////////////////////////////////////// // NapierPool AMM configuration constants ///////////////////////////////////////////////////////////////// // @notice Pool configuration Max logarithmic fee rate // @dev ln(1.05) in 18 decimals // @dev Computed by PrbMath library uint80 constant MAX_LN_FEE_RATE_ROOT = 48790164169431991; // @notice Max protocol fee percent. 100=100% uint8 constant MAX_PROTOCOL_FEE_PERCENT = 100; // 100% // @notice Min initial anchor int256 constant MIN_INITIAL_ANCHOR = 1e18;
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.19; library Errors { // Approx error ApproxFail(); error ApproxBinarySearchInputInvalid(); // Quoter error ApproxFailWithHint(bytes hint); // Factory error FactoryPoolAlreadyExists(); error FactoryUnderlyingMismatch(); error FactoryMaturityMismatch(); // Pool error PoolOnlyOwner(); error PoolInvalidParamName(); error PoolUnauthorizedCallback(); error PoolExpired(); error PoolInvariantViolated(); error PoolZeroAmountsInput(); error PoolZeroAmountsOutput(); error PoolZeroLnImpliedRate(); error PoolInsufficientBaseLptForTrade(); error PoolInsufficientBaseLptReceived(); error PoolInsufficientUnderlyingReceived(); error PoolExchangeRateBelowOne(int256 exchangeRate); error PoolProportionMustNotEqualOne(); error PoolRateScalarZero(); error PoolProportionTooHigh(); // Router error RouterInsufficientWETH(); error RouterInconsistentWETHPayment(); error RouterPoolNotFound(); error RouterTransactionTooOld(); error RouterInsufficientLpOut(); error RouterInsufficientTokenBalance(); error RouterInsufficientUnderlyingOut(); error RouterInsufficientYtOut(); error RouterExceededLimitUnderlyingIn(); error RouterInsufficientUnderlyingRepay(); error RouterInsufficientPtRepay(); error RouterCallbackNotNapierPool(); error RouterNonSituationSwapUnderlyingForYt(); error RouterInsufficientPyIssue(); // Generic error FailedToSendEther(); error NotWETH(); // Config error LnFeeRateRootTooHigh(); error ProtocolFeePercentTooHigh(); error InitialAnchorTooLow(); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => 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 override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override 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 `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` 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 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `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. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` 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. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol) pragma solidity ^0.8.0; import "./IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/cryptography/EIP712.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`. * However, to ensure consistency with the upgradeable transpiler, we will continue * to reserve a slot. * @custom:oz-renamed-from _PERMIT_TYPEHASH */ // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired 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); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // 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; uint256 private _status; constructor() { _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 { // On the first call to nonReentrant, _status will be _NOT_ENTERED require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _nonReentrantAfter() private { // 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) { return _status == _ENTERED; } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {IERC20} from "@openzeppelin/[email protected]/token/ERC20/IERC20.sol"; /// @notice Principal tokens (zero-coupon tokens) are redeemable for a single underlying EIP-20 token at a future timestamp. /// https://eips.ethereum.org/EIPS/eip-5095 interface IERC5095 is IERC20 { event Redeem(address indexed from, address indexed to, uint256 underlyingAmount); /// @dev Asset that is returned on redemption. function underlying() external view returns (address underlyingAddress); /// @dev Unix time at which redemption of fyToken for underlying are possible function maturity() external view returns (uint256 timestamp); /// @dev Converts a specified amount of principal to underlying function convertToUnderlying(uint256 principalAmount) external view returns (uint256 underlyingAmount); /// @dev Converts a specified amount of underlying to principal function convertToPrincipal(uint256 underlyingAmount) external view returns (uint256 principalAmount); /// @dev Gives the maximum amount an address holder can redeem in terms of the principal function maxRedeem(address holder) external view returns (uint256 maxPrincipalAmount); /// @dev Gives the amount in terms of underlying that the princiapl amount can be redeemed for plus accrual function previewRedeem(uint256 principalAmount) external view returns (uint256 underlyingAmount); /// @dev Burn fyToken after maturity for an amount of principal. function redeem(uint256 principalAmount, address to, address from) external returns (uint256 underlyingAmount); /// @dev Gives the maximum amount an address holder can withdraw in terms of the underlying function maxWithdraw(address holder) external view returns (uint256 maxUnderlyingAmount); /// @dev Gives the amount in terms of principal that the underlying amount can be withdrawn for plus accrual function previewWithdraw(uint256 underlyingAmount) external view returns (uint256 principalAmount); /// @dev Burn fyToken after maturity for an amount of underlying. function withdraw(uint256 underlyingAmount, address to, address from) external returns (uint256 principalAmount); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ 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]. */ 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 v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @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, it is bubbled up by this * function (like regular Solidity function calls). * * 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. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @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`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: AGPL-3.0-only /// @notice Taken from: https://github.com/transmissions11/solmate/blob/2001af43aedb46fdc2335d2a7714fb2dae7cfcd1/src/utils/FixedPointMathLib.sol pragma solidity >=0.8.0; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol) library FixedPointMathLib { /*////////////////////////////////////////////////////////////// SIMPLIFIED FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ uint256 internal constant MAX_UINT256 = 2 ** 256 - 1; uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up. } function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down. } function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up. } /*////////////////////////////////////////////////////////////// LOW LEVEL FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function mulDivDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) { revert(0, 0) } // Divide x * y by the denominator. z := div(mul(x, y), denominator) } } function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) { revert(0, 0) } // If x * y modulo the denominator is strictly greater than 0, // 1 is added to round up the division of x * y by the denominator. z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator)) } } function rpow(uint256 x, uint256 n, uint256 scalar) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := scalar } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store scalar in z for now. z := scalar } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, scalar) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, scalar) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, scalar) } } } } } /*////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { let y := x // We start y at x, which will help us make our initial estimate. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // We check y >= 2^(k + 8) but shift right by k bits // each branch to ensure that if x >= 256, then y >= 256. if iszero(lt(y, 0x10000000000000000000000000000000000)) { y := shr(128, y) z := shl(64, z) } if iszero(lt(y, 0x1000000000000000000)) { y := shr(64, y) z := shl(32, z) } if iszero(lt(y, 0x10000000000)) { y := shr(32, y) z := shl(16, z) } if iszero(lt(y, 0x1000000)) { y := shr(16, y) z := shl(8, z) } // Goal was to get z*z*y within a small factor of x. More iterations could // get y in a tighter range. Currently, we will have y in [256, 256*2^16). // We ensured y >= 256 so that the relative difference between y and y+1 is small. // That's not possible if x < 256 but we can just verify those cases exhaustively. // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256. // Correctness can be checked exhaustively for x < 256, so we assume y >= 256. // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps. // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256. // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18. // There is no overflow risk here since y < 2^136 after the first branch above. z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If x+1 is a perfect square, the Babylonian method cycles between // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case. // If you don't care whether the floor or ceil square root is returned, you can remove this statement. z := sub(z, lt(div(x, z), z)) } } function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Mod x by y. Note this will return // 0 instead of reverting if y is zero. z := mod(x, y) } } function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { // Divide x by y. Note this will return // 0 instead of reverting if y is zero. r := div(x, y) } } function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Add 1 to x * y if x % y > 0. Note this will // return 0 instead of reverting if y is zero. z := add(gt(mod(x, y), 0), div(x, y)) } } }
// 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 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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ 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 v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @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, InvalidSignatureV // Deprecated in v4.8 } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode 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 {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] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode 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 {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); 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. * * _Available since v4.2._ */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) { // 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); } // 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); } return (signer, RecoverError.NoError); } /** * @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) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) { // 32 is the length in bytes of hash, // enforced by the type signature above /// @solidity memory-safe-assembly assembly { mstore(0x00, "\x19Ethereum Signed Message:\n32") mstore(0x1c, hash) message := keccak256(0x00, 0x3c) } } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, "\x19\x01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) data := keccak256(ptr, 0x42) } } /** * @dev Returns an Ethereum Signed Data with intended validator, created from a * `validator` and `data` according to the version 0 of EIP-191. * * See {recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x00", validator, data)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.8; import "./ECDSA.sol"; import "../ShortStrings.sol"; import "../../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 specified in the EIP is very generic, and such a generic 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 their contracts 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. * * _Available since v3.4._ * * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment */ 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev See {EIP-5267}. * * _Available since v4.9._ */ function eip712Domain() public view virtual override returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { return ( hex"0f", // 01111 _name.toStringWithFallback(_nameFallback), _version.toStringWithFallback(_versionFallback), block.chainid, address(this), bytes32(0), new uint256[](0) ); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } }
// 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_UD2x18 } from "../ud2x18/Constants.sol"; import { UD2x18 } from "../ud2x18/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 must be greater than or equal to `uMIN_SD1x18`. /// - x must be less than or equal to `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 UD2x18. /// @dev Requirements: /// - x must be positive. /// - x must be less than or equal to `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 UD60x18. /// @dev Requirements: /// - x must be positive. 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 must be positive. 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 must be positive. /// - x must be less than or equal to `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 must be positive. /// - x must be less than or equal to `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 The maximum input permitted in {exp2}. int256 constant uEXP2_MAX_INPUT = 192e18 - 1; SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT); /// @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 must be greater than or equal to `MIN_SD59x18 / UNIT`. /// - x must be less than or equal to `MAX_SD59x18 / UNIT`. /// /// @param x The basic integer to convert. /// @param 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 a UD60x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD60x18. error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint256. error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40. error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 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 hte 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, 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 must be greater than `MIN_SD59x18`. /// /// @param x The SD59x18 number for which to calculate the absolute value. /// @param 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 must be less than or equal to `MAX_WHOLE_SD59x18`. /// /// @param x The SD59x18 number to ceil. /// @param 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. /// @param 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 must be less than 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(); // 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 is less than -59_794705707972522261, the result is zero. /// /// Requirements: /// - x must be less than 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 this is truncated to zero. if (xInt < -59_794705707972522261) { 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 must be greater than or equal to `MIN_WHOLE_SD59x18`. /// /// @param x The SD59x18 number to floor. /// @param 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. /// @param 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 must be greater than zero. /// /// @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 cannot be negative, since complex numbers are not supported. /// - x must be less than `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.intoUD2x18, 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 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_SD59x18 } from "../sd59x18/Constants.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { uMAX_UD2x18 } from "../ud2x18/Constants.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Casts a UD60x18 number into SD1x18. /// @dev Requirements: /// - x must be less than or equal to `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 UD2x18. /// @dev Requirements: /// - x must be less than or equal to `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 SD59x18. /// @dev Requirements: /// - x must be less than or equal to `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 must be less than or equal to `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 must be less than or equal to `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 must be less than or equal to `MAX_UD60x18 / UNIT`. /// /// @param x The basic integer to convert. /// @param 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 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 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 1. 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 must be less than or equal to `MAX_WHOLE_UD60x18`. /// /// @param x The UD60x18 number to ceil. /// @param 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. /// @param 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 must be less than 133_084258667509499441. /// /// @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 must be less than 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. /// @param 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. /// @param 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 must be greater than zero. /// /// @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 greater than `UNIT`, use the standard formula. if (xUint > uUNIT) { result = exp2(mul(log2(x), y)); } // Conversely, if x is less than `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 must be less than `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.intoUD2x18, Casting.intoSD59x18, 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 v4.9.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; import "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toString(int256 value) internal pure returns (string memory) { return string(abi.encodePacked(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) { 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] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol) pragma solidity ^0.8.8; import "./StorageSlot.sol"; // | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | // | length | 0x BB | type ShortString is bytes32; /** * @dev This library provides functions to convert short memory strings * into a `ShortString` type that can be used as an immutable variable. * * Strings of arbitrary length can be optimized using this library if * they are short enough (up to 31 bytes) by packing them with their * length (1 byte) in a single EVM word (32 bytes). Additionally, a * fallback mechanism can be used for every other case. * * Usage example: * * ```solidity * contract Named { * using ShortStrings for *; * * ShortString private immutable _name; * string private _nameFallback; * * constructor(string memory contractName) { * _name = contractName.toShortStringWithFallback(_nameFallback); * } * * function name() external view returns (string memory) { * return _name.toStringWithFallback(_nameFallback); * } * } * ``` */ library ShortStrings { // Used as an identifier for strings longer than 31 bytes. bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF; error StringTooLong(string str); error InvalidShortString(); /** * @dev Encode a string of at most 31 chars into a `ShortString`. * * This will trigger a `StringTooLong` error is the input string is too long. */ function toShortString(string memory str) internal pure returns (ShortString) { bytes memory bstr = bytes(str); if (bstr.length > 31) { revert StringTooLong(str); } return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length)); } /** * @dev Decode a `ShortString` back to a "normal" string. */ function toString(ShortString sstr) internal pure returns (string memory) { uint256 len = byteLength(sstr); // using `new string(len)` would work locally but is not memory safe. string memory str = new string(32); /// @solidity memory-safe-assembly assembly { mstore(str, len) mstore(add(str, 0x20), sstr) } return str; } /** * @dev Return the length of a `ShortString`. */ function byteLength(ShortString sstr) internal pure returns (uint256) { uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF; if (result > 31) { revert InvalidShortString(); } return result; } /** * @dev Encode a string into a `ShortString`, or write it to storage if it is too long. */ function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) { if (bytes(value).length < 32) { return toShortString(value); } else { StorageSlot.getStringSlot(store).value = value; return ShortString.wrap(_FALLBACK_SENTINEL); } } /** * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}. */ function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) { if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) { return toString(value); } else { return store; } } /** * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}. * * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of * actual characters as the UTF-8 encoding of a single character can span over multiple bytes. */ function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) { if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) { return byteLength(value); } else { return bytes(store).length; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol) pragma solidity ^0.8.0; 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 pragma solidity >=0.8.19; // Common.sol // // Common mathematical functions needed by 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 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 maximum 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); int256 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.intoUD2x18, Casting.intoUD60x18, Casting.intoUint256, Casting.intoUint128, Casting.intoUint40, Casting.unwrap } for SD1x18 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. uint256 constant uUNIT = 1e18; UD2x18 constant UNIT = UD2x18.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.intoSD1x18, Casting.intoSD59x18, Casting.intoUD60x18, Casting.intoUint256, Casting.intoUint128, Casting.intoUint40, Casting.unwrap } for UD2x18 global;
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ```solidity * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ * _Available since v4.9 for `string`, `bytes`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } /** * @dev Returns an `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; import "../Common.sol" as Common; import "./Errors.sol" as CastingErrors; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD2x18 } from "../ud2x18/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 the domain of SD1x18 is a subset of SD59x18. function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) { result = SD59x18.wrap(int256(SD1x18.unwrap(x))); } /// @notice Casts an SD1x18 number into UD2x18. /// - x must be positive. function intoUD2x18(SD1x18 x) pure returns (UD2x18 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUD2x18_Underflow(x); } result = UD2x18.wrap(uint64(xInt)); } /// @notice Casts an SD1x18 number into UD60x18. /// @dev Requirements: /// - x must be positive. 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 uint256. /// @dev Requirements: /// - x must be positive. 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 uint128. /// @dev Requirements: /// - x must be positive. 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 uint40. /// @dev Requirements: /// - x must be positive. /// - x must be less than or equal to `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 Errors; import { uMAX_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { UD2x18 } from "./ValueType.sol"; /// @notice Casts a UD2x18 number into SD1x18. /// - x must be less than or equal to `uMAX_SD1x18`. function intoSD1x18(UD2x18 x) pure returns (SD1x18 result) { uint64 xUint = UD2x18.unwrap(x); if (xUint > uint64(uMAX_SD1x18)) { revert Errors.PRBMath_UD2x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(xUint)); } /// @notice Casts a UD2x18 number into SD59x18. /// @dev There is no overflow check because the domain of UD2x18 is a subset of 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 the domain of UD2x18 is a subset of 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 the domain of UD2x18 is a subset of 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 the domain of UD2x18 is a subset of uint256. function intoUint256(UD2x18 x) pure returns (uint256 result) { result = uint256(UD2x18.unwrap(x)); } /// @notice Casts a UD2x18 number into uint40. /// @dev Requirements: /// - x must be less than or equal to `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 { SD1x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD2x18. error PRBMath_SD1x18_ToUD2x18_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD60x18. error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint128. error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint256. error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint40. error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x); /// @notice Thrown when trying to cast a 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 { UD2x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in SD1x18. error PRBMath_UD2x18_IntoSD1x18_Overflow(UD2x18 x); /// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40. error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);
{ "remappings": [ "forge-std/=lib/forge-std/src/", "@openzeppelin/[email protected]/=lib/openzeppelin-contracts/contracts/", "@napier/v1-tranche/=lib/napier-v1/", "@prb/math/=lib/prb-math/src/", "foundry-vyper/=lib/foundry-vyper/src/", "hardhat-deployer/=lib/hardhat-deployer/src/", "@prb/test/=lib/prb-math/lib/prb-test/src/", "ds-test/=lib/forge-std/lib/ds-test/src/", "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/", "eth-gas-reporter/=node_modules/eth-gas-reporter/", "forge-std/=lib/forge-std/src/", "hardhat/=node_modules/hardhat/", "napier-v1/=lib/napier-v1/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "openzeppelin/=lib/openzeppelin-contracts/contracts/", "prb-math/=lib/prb-math/src/", "prb-test/=lib/prb-math/lib/prb-test/src/", "tricrypto-ng/=lib/tricrypto-ng/contracts/" ], "optimizer": { "enabled": true, "runs": 500 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "none", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "paris", "viaIR": false, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[],"stateMutability":"payable","type":"constructor"},{"inputs":[],"name":"InvalidShortString","type":"error"},{"inputs":[],"name":"LnFeeRateRootTooHigh","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"}],"name":"PRBMath_SD59x18_Log_InputTooSmall","type":"error"},{"inputs":[{"internalType":"UD60x18","name":"x","type":"uint256"}],"name":"PRBMath_UD60x18_Exp2_InputTooBig","type":"error"},{"inputs":[{"internalType":"UD60x18","name":"x","type":"uint256"}],"name":"PRBMath_UD60x18_Exp_InputTooBig","type":"error"},{"inputs":[{"internalType":"int256","name":"exchangeRate","type":"int256"}],"name":"PoolExchangeRateBelowOne","type":"error"},{"inputs":[],"name":"PoolExpired","type":"error"},{"inputs":[],"name":"PoolInsufficientBaseLptForTrade","type":"error"},{"inputs":[],"name":"PoolInsufficientBaseLptReceived","type":"error"},{"inputs":[],"name":"PoolInsufficientUnderlyingReceived","type":"error"},{"inputs":[],"name":"PoolInvalidParamName","type":"error"},{"inputs":[],"name":"PoolInvariantViolated","type":"error"},{"inputs":[],"name":"PoolOnlyOwner","type":"error"},{"inputs":[],"name":"PoolProportionMustNotEqualOne","type":"error"},{"inputs":[],"name":"PoolProportionTooHigh","type":"error"},{"inputs":[],"name":"PoolRateScalarZero","type":"error"},{"inputs":[],"name":"PoolUnauthorizedCallback","type":"error"},{"inputs":[],"name":"PoolZeroAmountsInput","type":"error"},{"inputs":[],"name":"PoolZeroAmountsOutput","type":"error"},{"inputs":[],"name":"PoolZeroLnImpliedRate","type":"error"},{"inputs":[],"name":"ProtocolFeePercentTooHigh","type":"error"},{"inputs":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"liquidity","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"underlyingOut","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"baseLptOut","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"liquidity","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"underlyingUsed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"baseLptUsed","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"int256","name":"netUnderlying","type":"int256"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"},{"indexed":false,"internalType":"int256","name":"netPt","type":"int256"},{"indexed":false,"internalType":"uint256","name":"swapFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"protocolFee","type":"uint256"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"int256","name":"netUnderlying","type":"int256"},{"indexed":false,"internalType":"int256","name":"netBaseLpt","type":"int256"},{"indexed":false,"internalType":"uint256","name":"swapFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"protocolFee","type":"uint256"}],"name":"SwapBaseLpt","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"lnImpliedRate","type":"uint256"}],"name":"UpdateLnImpliedRate","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"underlyingInDesired","type":"uint256"},{"internalType":"uint256","name":"baseLptInDesired","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"addLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"contract IPoolFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAssets","outputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"initialAnchor","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastLnImpliedRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maturity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"principalTokens","outputs":[{"internalType":"contract IERC20[3]","name":"","type":"address[3]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"readState","outputs":[{"components":[{"internalType":"uint256","name":"totalBaseLptTimesN","type":"uint256"},{"internalType":"uint256","name":"totalUnderlying18","type":"uint256"},{"internalType":"uint256","name":"virtualPrice","type":"uint256"},{"internalType":"uint256","name":"scalarRoot","type":"uint256"},{"internalType":"uint256","name":"maturity","type":"uint256"},{"internalType":"uint256","name":"lnFeeRateRoot","type":"uint256"},{"internalType":"uint256","name":"protocolFeePercent","type":"uint256"},{"internalType":"uint256","name":"lastLnImpliedRate","type":"uint256"}],"internalType":"struct PoolState","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"}],"name":"removeLiquidity","outputs":[{"internalType":"uint256","name":"underlyingOut","type":"uint256"},{"internalType":"uint256","name":"baseLptOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"scalarRoot","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"paramName","type":"bytes32"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"setFeeParameter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"skim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"baseLptIn","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"swapExactBaseLpTokenForUnderlying","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"uint256","name":"ptIn","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swapPtForUnderlying","outputs":[{"internalType":"uint256","name":"underlyingOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"baseLptOut","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"swapUnderlyingForExactBaseLpToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"uint256","name":"ptOutDesired","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swapUnderlyingForPt","outputs":[{"internalType":"uint256","name":"underlyingIn","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalBaseLpt","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalUnderlying","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tricrypto","outputs":[{"internalType":"contract CurveTricryptoOptimizedWETH","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"underlying","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
60146102c08181527f4e617069657220506f6f6c204c5020546f6b656e0000000000000000000000006102e08190526001610300818152603160f81b61032052610340948552610360929092526103c0604052600e6103809081526d13985c1a595c941bdbdb0813141560921b6103a052600091909155919283926004620000888382620005f3565b506005620000978282620005f3565b50620000a991508390506006620004c9565b61012052620000ba816007620004c9565b61014052815160208084019190912060e052815190820120610100524660a0526200014860e05161010051604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201529081019290925260608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b60805250503060c05250336101608190526040805163274dbadb60e11b8152905160009291634e9b75b6916004808301926101409291908290030181865afa15801562000199573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001bf9190620007d9565b602080820180516060810151600a805492850151610260528351516102805292516040808201516001600160501b03166001600160501b031960ff9094166a010000000000000000000002939093166001600160581b031990941693909317919091179092556080909101516001600160a01b039081166102a0528351518082166101805284518401519182166101a0819052835163313ce56760e01b8152935195965090949193909263313ce56792600480830193928290030181865afa15801562000290573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620002b69190620008b0565b60ff166101c05282516040908101518051602080830151928401516001600160a01b038084166101e08190528186166102005290821661022052855163204f83f960e01b8152955193959193909263204f83f992600480820193918290030181865afa1580156200032b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620003519190620008d5565b6102405260405163095ea7b360e01b81526001600160a01b038681166004830152600019602483015284169063095ea7b3906044016020604051808303816000875af1158015620003a6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620003cc9190620008ef565b5060405163095ea7b360e01b81526001600160a01b038681166004830152600019602483015283169063095ea7b3906044016020604051808303816000875af11580156200041e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620004449190620008ef565b5060405163095ea7b360e01b81526001600160a01b038681166004830152600019602483015282169063095ea7b3906044016020604051808303816000875af115801562000496573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620004bc9190620008ef565b5050505050505062000988565b6000602083511015620004e957620004e18362000502565b9050620004fc565b81620004f68482620005f3565b5060ff90505b92915050565b600080829050601f8151111562000539578260405163305a27a960e01b815260040162000530919062000913565b60405180910390fd5b8051620005468262000963565b179392505050565b634e487b7160e01b600052604160045260246000fd5b600181811c908216806200057957607f821691505b6020821081036200059a57634e487b7160e01b600052602260045260246000fd5b50919050565b601f821115620005ee57600081815260208120601f850160051c81016020861015620005c95750805b601f850160051c820191505b81811015620005ea57828155600101620005d5565b5050505b505050565b81516001600160401b038111156200060f576200060f6200054e565b620006278162000620845462000564565b84620005a0565b602080601f8311600181146200065f5760008415620006465750858301515b600019600386901b1c1916600185901b178555620005ea565b600085815260208120601f198616915b8281101562000690578886015182559484019460019091019084016200066f565b5085821015620006af5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b604080519081016001600160401b0381118282101715620006e457620006e46200054e565b60405290565b604051606081016001600160401b0381118282101715620006e457620006e46200054e565b80516001600160a01b03811681146200072757600080fd5b919050565b805160ff811681146200072757600080fd5b600060a082840312156200075157600080fd5b60405160a081016001600160401b03811182821017156200077657620007766200054e565b6040908152835182526020808501519083015283015190915081906001600160501b0381168114620007a757600080fd5b6040820152620007ba606084016200072c565b6060820152620007cd608084016200070f565b60808201525092915050565b6000818303610140811215620007ee57600080fd5b620007f8620006bf565b60a08212156200080757600080fd5b62000811620006ea565b91506200081e846200070f565b825260206200082f8186016200070f565b8184015285605f8601126200084357600080fd5b6200084d620006ea565b8060a08701888111156200086057600080fd5b604088015b81811015620008875762000879816200070f565b845292840192840162000865565b508160408701528585526200089d89826200073e565b8486015250505050809250505092915050565b600060208284031215620008c357600080fd5b620008ce826200072c565b9392505050565b600060208284031215620008e857600080fd5b5051919050565b6000602082840312156200090257600080fd5b81518015158114620008ce57600080fd5b600060208083528351808285015260005b81811015620009425785810183015185820160400152820162000924565b506000604082860101526040601f19601f8301168501019250505092915050565b805160208083015191908110156200059a5760001960209190910360031b1b16919050565b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c0516101e05161020051610220516102405161026051610280516102a0516151fd62000c0e600039600081816103a5015281816107e801526108420152600081816104fe0152612d5201526000818161057a015281816124e10152612cda0152600081816102830152818161088401528181610afc015281816110700152818161123f0152818161174c015281816125070152612d0001526000611bfa01526000611bd201526000611bad0152600081816108ea015281816109180152818161094601528181610c1601528181610c4201528181610c6e015281816110d601528181611104015281816111320152818161135901528181611385015281816113b1015281816124b10152818161266101528181612b8e0152612cab01526000818161042b015281816104800152818161078301528181610820015281816109d801528181610cf601528181610d2901528181610f530152818161118f0152818161143a0152818161162f015281816117d3015281816119d70152611ff40152600081816104500152818161052d0152818161074b015281816107c6015281816109a301528181610b8001528181610cc901528181610e7401528181610f01015281816111c4015281816112c30152818161140d0152818161149f01528181611681015281816117a60152818161198501528181612030015281816123c60152612bd70152600081816105b601528181610d65015281816115240152818161188c0152611c3001526000611a8c01526000611a6101526000612ad101526000612aa901526000612a0401526000612a2e01526000612a5801526151fd6000f3fe608060405234801561001057600080fd5b506004361061021c5760003560e01c806367e4ac2c11610125578063a9059cbb116100ad578063c70920bc1161007c578063c70920bc146105d8578063d2135273146105f2578063d505accf14610605578063d798f86e14610618578063dd62ed3e1461064057600080fd5b8063a9059cbb14610562578063af247da314610575578063b751a0471461059c578063c45a0155146105b157600080fd5b806384b0196e116100f457806384b0196e146104de57806391e7c015146104f957806395d89b4114610520578063a0171ef514610528578063a457c2d71461054f57600080fd5b806367e4ac2c1461041d5780636f307dc31461047b57806370a08231146104a25780637ecebe00146104cb57600080fd5b806335ec597f116101a85780634157bc21116101775780634157bc211461038457806343bf8ab31461039757806346904840146103a05780634b5992df146103df57806362c0e33a146103f257600080fd5b806335ec597f146103435780633644e51514610356578063395093511461035e5780633a19e2301461037157600080fd5b8063204f83f9116101ef578063204f83f91461027e5780632390154f146102a557806323b872dd146102b85780632778c334146102cb578063313ce5671461033457600080fd5b806306fdde0314610221578063095ea7b31461023f57806318160ddd146102625780631dd19cb414610274575b600080fd5b610229610679565b6040516102369190614a17565b60405180910390f35b61025261024d366004614a3f565b61070b565b6040519015158152602001610236565b6003545b604051908152602001610236565b61027c610725565b005b6102667f000000000000000000000000000000000000000000000000000000000000000081565b6102666102b3366004614a6b565b610877565b6102526102c6366004614a9b565b610a76565b6102d3610a9a565b6040516102369190600061010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015292915050565b60405160128152602001610236565b610266610351366004614adc565b610aef565b61026661101a565b61025261036c366004614a3f565b611024565b61026661037f366004614a6b565b611063565b610266610392366004614adc565b611232565b610266600b5481565b6103c77f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610236565b6102666103ed366004614b88565b61173f565b600c54610405906001600160801b031681565b6040516001600160801b039091168152602001610236565b604080516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811682527f000000000000000000000000000000000000000000000000000000000000000016602082015201610236565b6103c77f000000000000000000000000000000000000000000000000000000000000000081565b6102666104b0366004614c5f565b6001600160a01b031660009081526001602052604090205490565b6102666104d9366004614c5f565b611a35565b6104e6611a53565b6040516102369796959493929190614c7c565b6102667f000000000000000000000000000000000000000000000000000000000000000081565b610229611adc565b6103c77f000000000000000000000000000000000000000000000000000000000000000081565b61025261055d366004614a3f565b611aeb565b610252610570366004614a3f565b611b82565b6102667f000000000000000000000000000000000000000000000000000000000000000081565b6105a4611b90565b6040516102369190614d12565b6103c77f000000000000000000000000000000000000000000000000000000000000000081565b600c5461040590600160801b90046001600160801b031681565b61027c610600366004614d4c565b611c24565b61027c610613366004614d6e565b611dc0565b61062b610626366004614c5f565b611f24565b60408051928352602083019190915201610236565b61026661064e366004614de5565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b60606004805461068890614e13565b80601f01602080910402602001604051908101604052809291908181526020018280546106b490614e13565b80156107015780601f106106d657610100808354040283529160200191610701565b820191906000526020600020905b8154815290600101906020018083116106e457829003601f168201915b5050505050905090565b6000336107198185856120b5565b60019150505b92915050565b61072d6121d9565b600c546001600160801b03600160801b82048116911660008161076f7f0000000000000000000000000000000000000000000000000000000000000000612232565b6107799190614e5d565b90506000836107a77f0000000000000000000000000000000000000000000000000000000000000000612232565b6107b19190614e5d565b9050811561080d5761080d6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000167f0000000000000000000000000000000000000000000000000000000000000000846122fa565b8015610867576108676001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000167f0000000000000000000000000000000000000000000000000000000000000000836122fa565b505050506108756001600055565b565b60006108816121d9565b427f0000000000000000000000000000000000000000000000000000000000000000116108c15760405163398b36db60e01b815260040160405180910390fd5b60006108cb61237a565b9050600080806108db8488612560565b91945092509050600061090e847f00000000000000000000000000000000000000000000000000000000000000006125c5565b9050600061093c847f00000000000000000000000000000000000000000000000000000000000000006125c5565b9050600061096a847f00000000000000000000000000000000000000000000000000000000000000006125c5565b90508260000361098d576040516354353b2760e01b815260040160405180910390fd5b610996876125ee565b6109cb6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308d6126e4565b6109ff6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168a856122fa565b6001600160a01b038916337f66d431b54da747831a1f20909a91a78bf991722fb6095c413fbf0918116dae15610a3486612722565b610a3d8e6127a9565b60408051928352602083019190915281018690526060810185905260800160405180910390a350909550505050505061071f6001600055565b600033610a848582856127c0565b610a8f85858561284c565b506001949350505050565b610ae260405180610100016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b610aea61237a565b905090565b6000610af96121d9565b427f000000000000000000000000000000000000000000000000000000000000000011610b395760405163398b36db60e01b815260040160405180910390fd5b610b416149a9565b600080600080610b4f61237a565b905089858c60038110610b6457610b64614e70565b6020020152604051633883e11960e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690633883e11990610bb8908890600190600401614ea9565b602060405180830381865afa158015610bd5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf99190614ec6565b935060008080610c098488612560565b91945092509050610c3a837f00000000000000000000000000000000000000000000000000000000000000006125c5565b9850610c66827f00000000000000000000000000000000000000000000000000000000000000006125c5565b9550610c92817f00000000000000000000000000000000000000000000000000000000000000006125c5565b945088600003610cb5576040516354353b2760e01b815260040160405180910390fd5b610cbe846125ee565b505050506000610ced7f0000000000000000000000000000000000000000000000000000000000000000612232565b90506000610d1a7f0000000000000000000000000000000000000000000000000000000000000000612232565b9050610d506001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168b896122fa565b60405163b27459ef60e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063b27459ef90602401602060405180830381865afa158015610db4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dd89190614edf565b610df4576040516237368760e61b815260040160405180910390fd5b3363fa483e72610e0389612722565b610e0c8e6127a9565b8c8c6040518563ffffffff1660e01b8152600401610e2d9493929190614f01565b600060405180830381600087803b158015610e4757600080fd5b505af1158015610e5b573d6000803e3d6000fd5b5050604051634515cef360e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169250634515cef39150610eae908990600090600401614f3e565b6020604051808303816000875af1158015610ecd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef19190614ec6565b50610efc8583614f59565b610f257f0000000000000000000000000000000000000000000000000000000000000000612232565b1015610f445760405163bf753d0160e01b815260040160405180910390fd5b610f4e8782614e5d565b610f777f0000000000000000000000000000000000000000000000000000000000000000612232565b1015610f9657604051630dbfca4560e11b815260040160405180910390fd5b50506001600160a01b038816337ff54b934b77620daa031e904076c3128079bcb07ca7a81f4235c504dc9c82eab4610fcd88612722565b8d610fd78e6127a9565b60408051938452602084019290925290820152606081018690526080810185905260a00160405180910390a3505050506110116001600055565b95945050505050565b6000610aea6129f7565b3360008181526002602090815260408083206001600160a01b0387168452909152812054909190610719908290869061105e908790614f59565b6120b5565b600061106d6121d9565b427f0000000000000000000000000000000000000000000000000000000000000000116110ad5760405163398b36db60e01b815260040160405180910390fd5b60006110b761237a565b9050600080806110c78488612b22565b9194509250905060006110fa847f00000000000000000000000000000000000000000000000000000000000000006125c5565b90506000611128847f00000000000000000000000000000000000000000000000000000000000000006125c5565b90506000611156847f00000000000000000000000000000000000000000000000000000000000000006125c5565b90508260000361117957604051634f3f1ff560e11b815260040160405180910390fd5b611182876125ee565b6111b76001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163330866126e4565b6111eb6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168a8c6122fa565b6001600160a01b038916337f66d431b54da747831a1f20909a91a78bf991722fb6095c413fbf0918116dae1561122086612722565b61122990614f6c565b610a3d8e612722565b600061123c6121d9565b427f00000000000000000000000000000000000000000000000000000000000000001161127c5760405163398b36db60e01b815260040160405180910390fd5b60008060008061128a61237a565b90506112946149a9565b89818c600381106112a7576112a7614e70565b6020020152604051633883e11960e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690633883e119906112fb908490600090600401614ea9565b602060405180830381865afa158015611318573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061133c9190614ec6565b94506000808061134c8589612b22565b9194509250905061137d837f00000000000000000000000000000000000000000000000000000000000000006125c5565b98506113a9827f00000000000000000000000000000000000000000000000000000000000000006125c5565b96506113d5817f00000000000000000000000000000000000000000000000000000000000000006125c5565b9550886000036113f857604051634f3f1ff560e11b815260040160405180910390fd5b611401856125ee565b505050505060006114317f0000000000000000000000000000000000000000000000000000000000000000612232565b9050600061145e7f0000000000000000000000000000000000000000000000000000000000000000612232565b6040516307329bcd60e01b815260048101879052602481018d9052600060448201819052606482018190526001600160a01b038c81166084840152929350917f000000000000000000000000000000000000000000000000000000000000000016906307329bcd9060a4016020604051808303816000875af11580156114e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061150c9190614ec6565b60405163b27459ef60e01b81523360048201529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063b27459ef90602401602060405180830381865afa158015611573573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115979190614edf565b6115b3576040516237368760e61b815260040160405180910390fd5b3363fa483e726115c2896127a9565b6115cb84612722565b8c8c6040518563ffffffff1660e01b81526004016115ec9493929190614f01565b600060405180830381600087803b15801561160657600080fd5b505af115801561161a573d6000803e3d6000fd5b50505050868261162a9190614f59565b6116537f0000000000000000000000000000000000000000000000000000000000000000612232565b101561167257604051633e43182560e01b815260040160405180910390fd5b61167c8684614e5d565b6116a57f0000000000000000000000000000000000000000000000000000000000000000612232565b10156116c457604051630dbfca4560e11b815260040160405180910390fd5b6001600160a01b038a16337ff54b934b77620daa031e904076c3128079bcb07ca7a81f4235c504dc9c82eab46116f98a6127a9565b8f61170386612722565b60408051938452602084019290925290820152606081018990526080810188905260a00160405180910390a35050505050506110116001600055565b60006117496121d9565b427f0000000000000000000000000000000000000000000000000000000000000000116117895760405163398b36db60e01b815260040160405180910390fd5b600c546001600160801b03600160801b82048116911660006117ca7f0000000000000000000000000000000000000000000000000000000000000000612232565b905060006117f77f0000000000000000000000000000000000000000000000000000000000000000612232565b9050600080600061180b87878c8f8f612b68565b9194509250905061182461181f8389614f59565b612eb6565b600c80546001600160801b03928316600160801b02921691909117905561184e61181f8288614f59565b600c80546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905560405163b27459ef60e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063b27459ef90602401602060405180830381865afa1580156118db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118ff9190614edf565b61191b576040516237368760e61b815260040160405180910390fd5b604051639f382e9b60e01b81523390639f382e9b9061194290859085908e90600401614f88565b600060405180830381600087803b15801561195c57600080fd5b505af1158015611970573d6000803e3d6000fd5b5050505080856119809190614f59565b6119a97f0000000000000000000000000000000000000000000000000000000000000000612232565b10156119c85760405163bf753d0160e01b815260040160405180910390fd5b6119d28285614f59565b6119fb7f0000000000000000000000000000000000000000000000000000000000000000612232565b1015611a1a57604051633e43182560e01b815260040160405180910390fd5b509095505050505050611a2d6001600055565b949350505050565b6001600160a01b03811660009081526008602052604081205461071f565b600060608082808083611a877f00000000000000000000000000000000000000000000000000000000000000006006612f1f565b611ab27f00000000000000000000000000000000000000000000000000000000000000006007612f1f565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b60606005805461068890614e13565b3360008181526002602090815260408083206001600160a01b038716845290915281205490919083811015611b755760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084015b60405180910390fd5b610a8f82868684036120b5565b60003361071981858561284c565b611b986149a9565b50604080516060810182526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811682527f0000000000000000000000000000000000000000000000000000000000000000811660208301527f0000000000000000000000000000000000000000000000000000000000000000169181019190915290565b336001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611c8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cb09190614fa7565b6001600160a01b031614611cd757604051630bcaf99960e21b815260040160405180910390fd5b816c1b1b91995954985d19549bdbdd609a1b03611d3b5766ad566553da1bb7811115611d1657604051633efe7b6f60e01b815260040160405180910390fd5b600a805469ffffffffffffffffffff191669ffffffffffffffffffff83161790555050565b817f70726f746f636f6c46656550657263656e74000000000000000000000000000003611da7576064811115611d8457604051630329b03560e11b815260040160405180910390fd5b600a80546aff000000000000000000001916600160501b60ff8416021790555050565b604051636d4eea9360e11b815260040160405180910390fd5b83421115611e105760405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606401611b6c565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9888888611e3f8c612fca565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090506000611e9a82612ff2565b90506000611eaa8287878761301f565b9050896001600160a01b0316816001600160a01b031614611f0d5760405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152606401611b6c565b611f188a8a8a6120b5565b50505050505050505050565b600080611f2f6121d9565b30600090815260016020526040902054600c546001600160801b03600160801b820481169116611f60828285613047565b909550935084158015611f71575083155b15611f8f576040516354353b2760e01b815260040160405180910390fd5b611f9c61181f8684614e5d565b600c80546001600160801b03928316600160801b029216919091179055611fc661181f8583614e5d565b600c80546fffffffffffffffffffffffffffffffff19166001600160801b03929092169190911790556120237f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031687876122fa565b6120576001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001687866122fa565b60408051848152602081018790529081018590526001600160a01b038716907f743033787f4738ff4d6a7225ce2bd0977ee5f86b91a902a58f5e4d0b297b46449060600160405180910390a25050506120b06001600055565b915091565b6001600160a01b0383166121175760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401611b6c565b6001600160a01b0382166121785760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401611b6c565b6001600160a01b0383811660008181526002602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b60026000540361222b5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401611b6c565b6002600055565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1790529051600091829182916001600160a01b038616916122899190614fc4565b600060405180830381855afa9150503d80600081146122c4576040519150601f19603f3d011682016040523d82523d6000602084013e6122c9565b606091505b50915091508180156122dd57506020815110155b6122e657600080fd5b80806020019051810190611a2d9190614ec6565b6040516001600160a01b03831660248201526044810182905261237590849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03167fffffffff00000000000000000000000000000000000000000000000000000000909316929092179091526130b9565b505050565b6123c260405180610100016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663bb7b8b806040518163ffffffff1660e01b8152600401602060405180830381865afa158015612422573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124469190614ec6565b604080516101008101909152600c54919250908190670de0b6b3a764000090849061247c906003906001600160801b0316614fe0565b6124869190614fe0565b612490919061500d565b8152600c546020909101906124d590600160801b90046001600160801b03167f000000000000000000000000000000000000000000000000000000000000000061318e565b815260208101929092527f000000000000000000000000000000000000000000000000000000000000000060408301527f00000000000000000000000000000000000000000000000000000000000000006060830152600a5469ffffffffffffffffffff81166080840152600160501b900460ff1660a0830152600b5460c090920191909152919050565b6000806000806000806125948861258f61258a8a60038d604001516125859190614fe0565b6131b0565b6127a9565b6131c5565b9250925092506125a38361322a565b95506125ae8261322a565b94506125b98161322a565b93505050509250925092565b60006125d2826012615021565b6125dd90600a61511e565b6125e7908461500d565b9392505050565b60e0810151600b5560408101516126299061260a906003614fe0565b825161261f90670de0b6b3a764000090614fe0565b61181f919061500d565b600c80546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905560208101516126859061181f907f00000000000000000000000000000000000000000000000000000000000000006125c5565b600c80546001600160801b03928316600160801b02921691909117905560e08101516040517f03209b52f068a7fc82f5defd3aff047085d3503077b90e6b018b83a90c140856916126d99190815260200190565b60405180910390a150565b6040516001600160a01b038085166024830152831660448201526064810182905261271c9085906323b872dd60e01b90608401612326565b50505050565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8211156127a55760405162461bcd60e51b815260206004820152602860248201527f53616665436173743a2076616c756520646f65736e27742066697420696e2061604482015267371034b73a191a9b60c11b6064820152608401611b6c565b5090565b60006127b482612722565b61071f9060001961512d565b6001600160a01b03838116600090815260026020908152604080832093861683529290522054600019811461271c578181101561283f5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401611b6c565b61271c84848484036120b5565b6001600160a01b0383166128b05760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401611b6c565b6001600160a01b0382166129125760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401611b6c565b6001600160a01b0383166000908152600160205260409020548181101561298a5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401611b6c565b6001600160a01b0380851660008181526001602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906129ea9086815260200190565b60405180910390a361271c565b6000306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016148015612a5057507f000000000000000000000000000000000000000000000000000000000000000046145b15612a7a57507f000000000000000000000000000000000000000000000000000000000000000090565b610aea604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b600080600080600080612b518861258f612b4c8a60038d60400151612b479190614fe0565b61327c565b612722565b9250925092506125a3612b6384613291565b61322a565b600080600080612b7760035490565b905080600003612db4576103e8612bc186612bb2897f000000000000000000000000000000000000000000000000000000000000000061318e565b612bbc9190614fe0565b61329f565b612bcb9190614e5d565b935085925084915060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663bb7b8b806040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c33573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c579190614ec6565b9050612c6660016103e8613387565b612d76604051806101000160405280670de0b6b3a764000084600388612c8c9190614fe0565b612c969190614fe0565b612ca0919061500d565b8152602001612ccf877f000000000000000000000000000000000000000000000000000000000000000061318e565b8152602081018490527f000000000000000000000000000000000000000000000000000000000000000060408201527f00000000000000000000000000000000000000000000000000000000000000006060820152600a5469ffffffffffffffffffff81166080830152600160501b900460ff1660a0820152600060c0909101527f0000000000000000000000000000000000000000000000000000000000000000613448565b600b8190556040519081527f03209b52f068a7fc82f5defd3aff047085d3503077b90e6b018b83a90c1408569060200160405180910390a150612e33565b600088612dc18388614fe0565b612dcb919061500d565b905060008a612dda848a614fe0565b612de4919061500d565b905080821015612e125781955086935082868c612e019190614fe0565b612e0b919061500d565b9450612e30565b94508693508482612e23828c614fe0565b612e2d919061500d565b93505b50505b83600003612e54576040516354353b2760e01b815260040160405180910390fd5b612e5e8785613387565b60408051858152602081018590529081018390526001600160a01b038816907fb4c03061fb5b7fed76389d5af8f2e0ddb09f8c70d1333abbb62582835e10accb9060600160405180910390a250955095509592505050565b60006001600160801b038211156127a55760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b6064820152608401611b6c565b606060ff8314612f3957612f3283613480565b905061071f565b818054612f4590614e13565b80601f0160208091040260200160405190810160405280929190818152602001828054612f7190614e13565b8015612fbe5780601f10612f9357610100808354040283529160200191612fbe565b820191906000526020600020905b815481529060010190602001808311612fa157829003601f168201915b5050505050905061071f565b6001600160a01b03811660009081526008602052604090208054600181018255905b50919050565b600061071f612fff6129f7565b8360405161190160f01b8152600281019290925260228201526042902090565b6000806000613030878787876134bf565b9150915061303d81613583565b5095945050505050565b6000808260000361306b57604051634f3f1ff560e11b815260040160405180910390fd5b600061307660035490565b9050806130838786614fe0565b61308d919061500d565b92508061309a8686614fe0565b6130a4919061500d565b91506130b030856136d0565b50935093915050565b600061310e826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166138049092919063ffffffff16565b905080516000148061312f57508080602001905181019061312f9190614edf565b6123755760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401611b6c565b600061319b826012615021565b6131a690600a61511e565b6125e79084614fe0565b60006125e78383670de0b6b3a7640000613813565b6000806000836131d88660000151612722565b136131f657604051634d7393f160e11b815260040160405180910390fd5b600061320186613831565b905061320e8682876138ab565b9195509350915061322286828787866139dc565b509250925092565b6000808212156127a55760405162461bcd60e51b815260206004820181905260248201527f53616665436173743a2076616c7565206d75737420626520706f7369746976656044820152606401611b6c565b60006125e78383670de0b6b3a7640000613a82565b600061071f8260001961512d565b6000816000036132b157506000919050565b600060016132be84613aa8565b901c6001901b905060018184816132d7576132d7614ff7565b048201901c905060018184816132ef576132ef614ff7565b048201901c9050600181848161330757613307614ff7565b048201901c9050600181848161331f5761331f614ff7565b048201901c9050600181848161333757613337614ff7565b048201901c9050600181848161334f5761334f614ff7565b048201901c9050600181848161336757613367614ff7565b048201901c90506125e78182858161338157613381614ff7565b04613b3c565b6001600160a01b0382166133dd5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401611b6c565b80600360008282546133ef9190614f59565b90915550506001600160a01b0382166000818152600160209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b60008042846080015161345b9190614e5d565b905060006134698583613b52565b905061101185600001518660200151838786613baa565b6060600061348d83613c03565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311156134f6575060009050600361357a565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa15801561354a573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166135735760006001925092505061357a565b9150600090505b94509492505050565b60008160048111156135975761359761515d565b0361359f5750565b60018160048111156135b3576135b361515d565b036136005760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401611b6c565b60028160048111156136145761361461515d565b036136615760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401611b6c565b60038160048111156136755761367561515d565b036136cd5760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401611b6c565b50565b6001600160a01b0382166137305760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401611b6c565b6001600160a01b038216600090815260016020526040902054818110156137a45760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401611b6c565b6001600160a01b03831660008181526001602090815260408083208686039055600380548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6060611a2d8484600085613c2b565b600082600019048411830215820261382a57600080fd5b5091020490565b61385560405180606001604052806000815260200160008152602001600081525090565b60004283608001516138679190614e5d565b90506138738382613b52565b808352835160e0850151602086015161388c9385613d06565b602083015260a08301516138a09082613d70565b604083015250919050565b6000806000806138d1612b4c8860000151896020015189600001518a602001518a613da7565b905060006138e76138e28784613e63565b613291565b905060008087131561396457600061390c896040015185613e6390919063ffffffff16565b9050670de0b6b3a764000081121561393a57604051631586184160e31b815260048101829052602401611b6c565b61395c8960400151670de0b6b3a76400006139559190615173565b8490613e78565b915050613996565b60408801516139939061397f81670de0b6b3a7640000615173565b613989908561512d565b6138e2919061519a565b90505b60006139a28284615173565b9050600060646139b58c60c00151612722565b6139bf908561512d565b6139c9919061519a565b919b929a50909850909650505050505050565b6139f7836139ed8760000151612722565b612b639190615173565b8552613a1c612b63613a0983856151c8565b613a168860200151612722565b90613e8d565b60208601526080850151600090613a34904290614e5d565b9050613a53866000015187602001518760000151886020015185613baa565b60e08701819052600003613a7a57604051634800fe7f60e01b815260040160405180910390fd5b505050505050565b6000826000190484118302158202613a9957600080fd5b50910281810615159190040190565b600080608083901c15613abd57608092831c92015b604083901c15613acf57604092831c92015b602083901c15613ae157602092831c92015b601083901c15613af357601092831c92015b600883901c15613b0557600892831c92015b600483901c15613b1757600492831c92015b600283901c15613b2957600292831c92015b600183901c1561071f5760010192915050565b6000818310613b4b57816125e7565b5090919050565b60008082613b656201518061016d614fe0565b8560600151613b749190614fe0565b613b7e919061500d565b905080600003613ba15760405163117aed9560e21b815260040160405180910390fd5b611a2d81612722565b600080613bbe612b4c888888886000613da7565b90506000613bd1613bce83613ed4565b90565b905083613be36201518061016d614fe0565b613bed9083614fe0565b613bf7919061500d565b98975050505050505050565b600060ff8216601f81111561071f57604051632cd44ac360e21b815260040160405180910390fd5b606082471015613c8c5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401611b6c565b600080866001600160a01b03168587604051613ca89190614fc4565b60006040518083038185875af1925050503d8060008114613ce5576040519150601f19603f3d011682016040523d82523d6000602084013e613cea565b606091505b5091509150613cfb87838387613f0b565b979650505050505050565b600080613d138684613d70565b9050670de0b6b3a7640000811215613d2a57600080fd5b6000613d40613d39878a614f59565b8990613f84565b90506000613d4d82613f99565b9050613d598187613e63565b613d639084615173565b9998505050505050505050565b600080613d826201518061016d614fe0565b613d8c8486614fe0565b613d96919061500d565b9050611a2d612b4c613bce83613ff2565b600080613db7836139ed89612722565b90506000613dcf613dc8888a614f59565b8390613f84565b9050670d529ae9e8600000811115613dfa57604051635677eea360e01b815260040160405180910390fd5b6000613e0582613f99565b9050600086613e14838a613e63565b613e1e91906151c8565b9050670de0b6b3a7640000811215613e4c57604051631586184160e31b815260048101829052602401611b6c565b613e558161322a565b9a9950505050505050505050565b60006125e783670de0b6b3a764000084614040565b60006125e78383670de0b6b3a7640000614040565b600081831215613eca5760405162461bcd60e51b81526020600482015260086024820152676e6567617469766560c01b6044820152606401611b6c565b6125e78284615173565b600061071f6714057b7ef767814f670de0b6b3a7640000613ef7613bce86614068565b613f01919061512d565b613bce919061519a565b60608315613f7a578251600003613f73576001600160a01b0385163b613f735760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401611b6c565b5081611a2d565b611a2d83836141ce565b60006125e783670de0b6b3a764000084613813565b6000670de0b6b3a76400008203613fc357604051631b65cfed60e31b815260040160405180910390fd5b6000613fe4612b4c613fdd85670de0b6b3a7640000614e5d565b8590613f84565b90506125e7613bce82613ed4565b600081680736ea4425c11ac63081111561402257604051630d7b1d6560e11b815260048101849052602401611b6c565b6714057b7ef767814f8102611a2d670de0b6b3a764000082046141f8565b60008061404d848661512d565b905082818161405e5761405e614ff7565b0595945050505050565b60008181811361408e5760405163059b101b60e01b815260048101849052602401611b6c565b6000670de0b6b3a764000082126140a7575060016140cd565b50600019816ec097ce7bc90715b34b9f1000000000816140c9576140c9614ff7565b0591505b6000614150670de0b6b3a7640000840560016001600160801b03821160071b91821c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211871b91821c969096119490961792909217171791909117919091171790565b9050670de0b6b3a7640000810283821d670de0b6b3a763ffff19810161417d575091909102949350505050565b671bc16d674ec800006706f05b59d3b200005b60008113156141c357670de0b6b3a76400008380020592508183126141bb579283019260019290921d915b60011d614190565b509184029182613bf7565b8151156141de5781518083602001fd5b8060405162461bcd60e51b8152600401611b6c9190614a17565b600081680a688906bd8affffff8111156142285760405163b3b6ba1f60e01b815260048101849052602401611b6c565b6000614240670de0b6b3a7640000604084901b61500d565b9050611a2d613bce82600160bf1b67ff000000000000008216156143565767800000000000000082161561427d5768016a09e667f3bcc9090260401c5b67400000000000000082161561429c576801306fe0a31b7152df0260401c5b6720000000000000008216156142bb576801172b83c7d517adce0260401c5b6710000000000000008216156142da5768010b5586cf9890f62a0260401c5b6708000000000000008216156142f9576801059b0d31585743ae0260401c5b67040000000000000082161561431857680102c9a3e778060ee70260401c5b6702000000000000008216156143375768010163da9fb33356d80260401c5b67010000000000000082161561435657680100b1afa5abcbed610260401c5b66ff0000000000008216156144555766800000000000008216156143835768010058c86da1c09ea20260401c5b66400000000000008216156143a1576801002c605e2e8cec500260401c5b66200000000000008216156143bf57680100162f3904051fa10260401c5b66100000000000008216156143dd576801000b175effdc76ba0260401c5b66080000000000008216156143fb57680100058ba01fb9f96d0260401c5b66040000000000008216156144195768010002c5cc37da94920260401c5b6602000000000000821615614437576801000162e525ee05470260401c5b66010000000000008216156144555768010000b17255775c040260401c5b65ff000000000082161561454b5765800000000000821615614480576801000058b91b5bc9ae0260401c5b6540000000000082161561449d57680100002c5c89d5ec6d0260401c5b652000000000008216156144ba5768010000162e43f4f8310260401c5b651000000000008216156144d757680100000b1721bcfc9a0260401c5b650800000000008216156144f45768010000058b90cf1e6e0260401c5b65040000000000821615614511576801000002c5c863b73f0260401c5b6502000000000082161561452e57680100000162e430e5a20260401c5b6501000000000082161561454b576801000000b1721835510260401c5b64ff000000008216156146385764800000000082161561457457680100000058b90c0b490260401c5b6440000000008216156145905768010000002c5c8601cc0260401c5b6420000000008216156145ac576801000000162e42fff00260401c5b6410000000008216156145c85768010000000b17217fbb0260401c5b6408000000008216156145e4576801000000058b90bfce0260401c5b64040000000082161561460057680100000002c5c85fe30260401c5b64020000000082161561461c5768010000000162e42ff10260401c5b64010000000082161561463857680100000000b17217f80260401c5b63ff00000082161561471c57638000000082161561465f5768010000000058b90bfc0260401c5b634000000082161561467a576801000000002c5c85fe0260401c5b632000000082161561469557680100000000162e42ff0260401c5b63100000008216156146b0576801000000000b17217f0260401c5b63080000008216156146cb57680100000000058b90c00260401c5b63040000008216156146e65768010000000002c5c8600260401c5b6302000000821615614701576801000000000162e4300260401c5b630100000082161561471c5768010000000000b172180260401c5b62ff00008216156147f75762800000821615614741576801000000000058b90c0260401c5b6240000082161561475b57680100000000002c5c860260401c5b622000008216156147755768010000000000162e430260401c5b6210000082161561478f57680100000000000b17210260401c5b620800008216156147a95768010000000000058b910260401c5b620400008216156147c3576801000000000002c5c80260401c5b620200008216156147dd57680100000000000162e40260401c5b620100008216156147f7576801000000000000b1720260401c5b61ff008216156148c95761800082161561481a57680100000000000058b90260401c5b6140008216156148335768010000000000002c5d0260401c5b61200082161561484c576801000000000000162e0260401c5b6110008216156148655768010000000000000b170260401c5b61080082161561487e576801000000000000058c0260401c5b61040082161561489757680100000000000002c60260401c5b6102008216156148b057680100000000000001630260401c5b6101008216156148c957680100000000000000b10260401c5b60ff8216156149925760808216156148ea57680100000000000000590260401c5b6040821615614902576801000000000000002c0260401c5b602082161561491a57680100000000000000160260401c5b6010821615614932576801000000000000000b0260401c5b600882161561494a57680100000000000000060260401c5b600482161561496257680100000000000000030260401c5b600282161561497a57680100000000000000010260401c5b600182161561499257680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b60405180606001604052806003906020820280368337509192915050565b60005b838110156149e25781810151838201526020016149ca565b50506000910152565b60008151808452614a038160208601602086016149c7565b601f01601f19169290920160200192915050565b6020815260006125e760208301846149eb565b6001600160a01b03811681146136cd57600080fd5b60008060408385031215614a5257600080fd5b8235614a5d81614a2a565b946020939093013593505050565b60008060408385031215614a7e57600080fd5b823591506020830135614a9081614a2a565b809150509250929050565b600080600060608486031215614ab057600080fd5b8335614abb81614a2a565b92506020840135614acb81614a2a565b929592945050506040919091013590565b600080600080600060808688031215614af457600080fd5b85359450602086013593506040860135614b0d81614a2a565b9250606086013567ffffffffffffffff80821115614b2a57600080fd5b818801915088601f830112614b3e57600080fd5b813581811115614b4d57600080fd5b896020828501011115614b5f57600080fd5b9699959850939650602001949392505050565b634e487b7160e01b600052604160045260246000fd5b60008060008060808587031215614b9e57600080fd5b84359350602085013592506040850135614bb781614a2a565b9150606085013567ffffffffffffffff80821115614bd457600080fd5b818701915087601f830112614be857600080fd5b813581811115614bfa57614bfa614b72565b604051601f8201601f19908116603f01168101908382118183101715614c2257614c22614b72565b816040528281528a6020848701011115614c3b57600080fd5b82602086016020830137600060208483010152809550505050505092959194509250565b600060208284031215614c7157600080fd5b81356125e781614a2a565b60ff60f81b881681526000602060e081840152614c9c60e084018a6149eb565b8381036040850152614cae818a6149eb565b606085018990526001600160a01b038816608086015260a0850187905284810360c0860152855180825283870192509083019060005b81811015614d0057835183529284019291840191600101614ce4565b50909c9b505050505050505050505050565b60608101818360005b6003811015614d435781516001600160a01b0316835260209283019290910190600101614d1b565b50505092915050565b60008060408385031215614d5f57600080fd5b50508035926020909101359150565b600080600080600080600060e0888a031215614d8957600080fd5b8735614d9481614a2a565b96506020880135614da481614a2a565b95506040880135945060608801359350608088013560ff81168114614dc857600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215614df857600080fd5b8235614e0381614a2a565b91506020830135614a9081614a2a565b600181811c90821680614e2757607f821691505b602082108103612fec57634e487b7160e01b600052602260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8181038181111561071f5761071f614e47565b634e487b7160e01b600052603260045260246000fd5b8060005b600381101561271c578151845260209384019390910190600101614e8a565b60808101614eb78285614e86565b82151560608301529392505050565b600060208284031215614ed857600080fd5b5051919050565b600060208284031215614ef157600080fd5b815180151581146125e757600080fd5b84815283602082015260606040820152816060820152818360808301376000818301608090810191909152601f909201601f191601019392505050565b60808101614f4c8285614e86565b8260608301529392505050565b8082018082111561071f5761071f614e47565b6000600160ff1b8201614f8157614f81614e47565b5060000390565b83815282602082015260606040820152600061101160608301846149eb565b600060208284031215614fb957600080fd5b81516125e781614a2a565b60008251614fd68184602087016149c7565b9190910192915050565b808202811582820484141761071f5761071f614e47565b634e487b7160e01b600052601260045260246000fd5b60008261501c5761501c614ff7565b500490565b60ff828116828216039081111561071f5761071f614e47565b600181815b8085111561507557816000190482111561505b5761505b614e47565b8085161561506857918102915b93841c939080029061503f565b509250929050565b60008261508c5750600161071f565b816150995750600061071f565b81600181146150af57600281146150b9576150d5565b600191505061071f565b60ff8411156150ca576150ca614e47565b50506001821b61071f565b5060208310610133831016604e8410600b84101617156150f8575081810a61071f565b615102838361503a565b806000190482111561511657615116614e47565b029392505050565b60006125e760ff84168361507d565b80820260008212600160ff1b8414161561514957615149614e47565b818105831482151761071f5761071f614e47565b634e487b7160e01b600052602160045260246000fd5b818103600083128015838313168383128216171561519357615193614e47565b5092915050565b6000826151a9576151a9614ff7565b600160ff1b8214600019841416156151c3576151c3614e47565b500590565b80820182811260008312801582168215821617156151e8576151e8614e47565b50509291505056fea164736f6c6343000813000a
Deployed Bytecode
0x608060405234801561001057600080fd5b506004361061021c5760003560e01c806367e4ac2c11610125578063a9059cbb116100ad578063c70920bc1161007c578063c70920bc146105d8578063d2135273146105f2578063d505accf14610605578063d798f86e14610618578063dd62ed3e1461064057600080fd5b8063a9059cbb14610562578063af247da314610575578063b751a0471461059c578063c45a0155146105b157600080fd5b806384b0196e116100f457806384b0196e146104de57806391e7c015146104f957806395d89b4114610520578063a0171ef514610528578063a457c2d71461054f57600080fd5b806367e4ac2c1461041d5780636f307dc31461047b57806370a08231146104a25780637ecebe00146104cb57600080fd5b806335ec597f116101a85780634157bc21116101775780634157bc211461038457806343bf8ab31461039757806346904840146103a05780634b5992df146103df57806362c0e33a146103f257600080fd5b806335ec597f146103435780633644e51514610356578063395093511461035e5780633a19e2301461037157600080fd5b8063204f83f9116101ef578063204f83f91461027e5780632390154f146102a557806323b872dd146102b85780632778c334146102cb578063313ce5671461033457600080fd5b806306fdde0314610221578063095ea7b31461023f57806318160ddd146102625780631dd19cb414610274575b600080fd5b610229610679565b6040516102369190614a17565b60405180910390f35b61025261024d366004614a3f565b61070b565b6040519015158152602001610236565b6003545b604051908152602001610236565b61027c610725565b005b6102667f000000000000000000000000000000000000000000000000000000006772435581565b6102666102b3366004614a6b565b610877565b6102526102c6366004614a9b565b610a76565b6102d3610a9a565b6040516102369190600061010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015292915050565b60405160128152602001610236565b610266610351366004614adc565b610aef565b61026661101a565b61025261036c366004614a3f565b611024565b61026661037f366004614a6b565b611063565b610266610392366004614adc565b611232565b610266600b5481565b6103c77f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d81565b6040516001600160a01b039091168152602001610236565b6102666103ed366004614b88565b61173f565b600c54610405906001600160801b031681565b6040516001600160801b039091168152602001610236565b604080516001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2811682527f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde16602082015201610236565b6103c77f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b6102666104b0366004614c5f565b6001600160a01b031660009081526001602052604090205490565b6102666104d9366004614c5f565b611a35565b6104e6611a53565b6040516102369796959493929190614c7c565b6102667f0000000000000000000000000000000000000000000000000e3872be3bd5ae0081565b610229611adc565b6103c77f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde81565b61025261055d366004614a3f565b611aeb565b610252610570366004614a3f565b611b82565b6102667f000000000000000000000000000000000000000000000004d2c3d7905734ee0081565b6105a4611b90565b6040516102369190614d12565b6103c77f00000000000000000000000017354e8e7518599c7f6b7095a6706766e4e4dc6181565b600c5461040590600160801b90046001600160801b031681565b61027c610600366004614d4c565b611c24565b61027c610613366004614d6e565b611dc0565b61062b610626366004614c5f565b611f24565b60408051928352602083019190915201610236565b61026661064e366004614de5565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b60606004805461068890614e13565b80601f01602080910402602001604051908101604052809291908181526020018280546106b490614e13565b80156107015780601f106106d657610100808354040283529160200191610701565b820191906000526020600020905b8154815290600101906020018083116106e457829003601f168201915b5050505050905090565b6000336107198185856120b5565b60019150505b92915050565b61072d6121d9565b600c546001600160801b03600160801b82048116911660008161076f7f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde612232565b6107799190614e5d565b90506000836107a77f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2612232565b6107b19190614e5d565b9050811561080d5761080d6001600160a01b037f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde167f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d846122fa565b8015610867576108676001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2167f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d836122fa565b505050506108756001600055565b565b60006108816121d9565b427f0000000000000000000000000000000000000000000000000000000067724355116108c15760405163398b36db60e01b815260040160405180910390fd5b60006108cb61237a565b9050600080806108db8488612560565b91945092509050600061090e847f00000000000000000000000000000000000000000000000000000000000000126125c5565b9050600061093c847f00000000000000000000000000000000000000000000000000000000000000126125c5565b9050600061096a847f00000000000000000000000000000000000000000000000000000000000000126125c5565b90508260000361098d576040516354353b2760e01b815260040160405180910390fd5b610996876125ee565b6109cb6001600160a01b037f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde1633308d6126e4565b6109ff6001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2168a856122fa565b6001600160a01b038916337f66d431b54da747831a1f20909a91a78bf991722fb6095c413fbf0918116dae15610a3486612722565b610a3d8e6127a9565b60408051928352602083019190915281018690526060810185905260800160405180910390a350909550505050505061071f6001600055565b600033610a848582856127c0565b610a8f85858561284c565b506001949350505050565b610ae260405180610100016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b610aea61237a565b905090565b6000610af96121d9565b427f000000000000000000000000000000000000000000000000000000006772435511610b395760405163398b36db60e01b815260040160405180910390fd5b610b416149a9565b600080600080610b4f61237a565b905089858c60038110610b6457610b64614e70565b6020020152604051633883e11960e01b81526001600160a01b037f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde1690633883e11990610bb8908890600190600401614ea9565b602060405180830381865afa158015610bd5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf99190614ec6565b935060008080610c098488612560565b91945092509050610c3a837f00000000000000000000000000000000000000000000000000000000000000126125c5565b9850610c66827f00000000000000000000000000000000000000000000000000000000000000126125c5565b9550610c92817f00000000000000000000000000000000000000000000000000000000000000126125c5565b945088600003610cb5576040516354353b2760e01b815260040160405180910390fd5b610cbe846125ee565b505050506000610ced7f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde612232565b90506000610d1a7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2612232565b9050610d506001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2168b896122fa565b60405163b27459ef60e01b81523360048201527f00000000000000000000000017354e8e7518599c7f6b7095a6706766e4e4dc616001600160a01b03169063b27459ef90602401602060405180830381865afa158015610db4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dd89190614edf565b610df4576040516237368760e61b815260040160405180910390fd5b3363fa483e72610e0389612722565b610e0c8e6127a9565b8c8c6040518563ffffffff1660e01b8152600401610e2d9493929190614f01565b600060405180830381600087803b158015610e4757600080fd5b505af1158015610e5b573d6000803e3d6000fd5b5050604051634515cef360e01b81526001600160a01b037f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde169250634515cef39150610eae908990600090600401614f3e565b6020604051808303816000875af1158015610ecd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef19190614ec6565b50610efc8583614f59565b610f257f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde612232565b1015610f445760405163bf753d0160e01b815260040160405180910390fd5b610f4e8782614e5d565b610f777f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2612232565b1015610f9657604051630dbfca4560e11b815260040160405180910390fd5b50506001600160a01b038816337ff54b934b77620daa031e904076c3128079bcb07ca7a81f4235c504dc9c82eab4610fcd88612722565b8d610fd78e6127a9565b60408051938452602084019290925290820152606081018690526080810185905260a00160405180910390a3505050506110116001600055565b95945050505050565b6000610aea6129f7565b3360008181526002602090815260408083206001600160a01b0387168452909152812054909190610719908290869061105e908790614f59565b6120b5565b600061106d6121d9565b427f0000000000000000000000000000000000000000000000000000000067724355116110ad5760405163398b36db60e01b815260040160405180910390fd5b60006110b761237a565b9050600080806110c78488612b22565b9194509250905060006110fa847f00000000000000000000000000000000000000000000000000000000000000126125c5565b90506000611128847f00000000000000000000000000000000000000000000000000000000000000126125c5565b90506000611156847f00000000000000000000000000000000000000000000000000000000000000126125c5565b90508260000361117957604051634f3f1ff560e11b815260040160405180910390fd5b611182876125ee565b6111b76001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2163330866126e4565b6111eb6001600160a01b037f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde168a8c6122fa565b6001600160a01b038916337f66d431b54da747831a1f20909a91a78bf991722fb6095c413fbf0918116dae1561122086612722565b61122990614f6c565b610a3d8e612722565b600061123c6121d9565b427f00000000000000000000000000000000000000000000000000000000677243551161127c5760405163398b36db60e01b815260040160405180910390fd5b60008060008061128a61237a565b90506112946149a9565b89818c600381106112a7576112a7614e70565b6020020152604051633883e11960e01b81526001600160a01b037f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde1690633883e119906112fb908490600090600401614ea9565b602060405180830381865afa158015611318573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061133c9190614ec6565b94506000808061134c8589612b22565b9194509250905061137d837f00000000000000000000000000000000000000000000000000000000000000126125c5565b98506113a9827f00000000000000000000000000000000000000000000000000000000000000126125c5565b96506113d5817f00000000000000000000000000000000000000000000000000000000000000126125c5565b9550886000036113f857604051634f3f1ff560e11b815260040160405180910390fd5b611401856125ee565b505050505060006114317f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde612232565b9050600061145e7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2612232565b6040516307329bcd60e01b815260048101879052602481018d9052600060448201819052606482018190526001600160a01b038c81166084840152929350917f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde16906307329bcd9060a4016020604051808303816000875af11580156114e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061150c9190614ec6565b60405163b27459ef60e01b81523360048201529091507f00000000000000000000000017354e8e7518599c7f6b7095a6706766e4e4dc616001600160a01b03169063b27459ef90602401602060405180830381865afa158015611573573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115979190614edf565b6115b3576040516237368760e61b815260040160405180910390fd5b3363fa483e726115c2896127a9565b6115cb84612722565b8c8c6040518563ffffffff1660e01b81526004016115ec9493929190614f01565b600060405180830381600087803b15801561160657600080fd5b505af115801561161a573d6000803e3d6000fd5b50505050868261162a9190614f59565b6116537f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2612232565b101561167257604051633e43182560e01b815260040160405180910390fd5b61167c8684614e5d565b6116a57f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde612232565b10156116c457604051630dbfca4560e11b815260040160405180910390fd5b6001600160a01b038a16337ff54b934b77620daa031e904076c3128079bcb07ca7a81f4235c504dc9c82eab46116f98a6127a9565b8f61170386612722565b60408051938452602084019290925290820152606081018990526080810188905260a00160405180910390a35050505050506110116001600055565b60006117496121d9565b427f0000000000000000000000000000000000000000000000000000000067724355116117895760405163398b36db60e01b815260040160405180910390fd5b600c546001600160801b03600160801b82048116911660006117ca7f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde612232565b905060006117f77f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2612232565b9050600080600061180b87878c8f8f612b68565b9194509250905061182461181f8389614f59565b612eb6565b600c80546001600160801b03928316600160801b02921691909117905561184e61181f8288614f59565b600c80546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905560405163b27459ef60e01b81523360048201527f00000000000000000000000017354e8e7518599c7f6b7095a6706766e4e4dc616001600160a01b03169063b27459ef90602401602060405180830381865afa1580156118db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118ff9190614edf565b61191b576040516237368760e61b815260040160405180910390fd5b604051639f382e9b60e01b81523390639f382e9b9061194290859085908e90600401614f88565b600060405180830381600087803b15801561195c57600080fd5b505af1158015611970573d6000803e3d6000fd5b5050505080856119809190614f59565b6119a97f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde612232565b10156119c85760405163bf753d0160e01b815260040160405180910390fd5b6119d28285614f59565b6119fb7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2612232565b1015611a1a57604051633e43182560e01b815260040160405180910390fd5b509095505050505050611a2d6001600055565b949350505050565b6001600160a01b03811660009081526008602052604081205461071f565b600060608082808083611a877f4e617069657220506f6f6c204c5020546f6b656e0000000000000000000000146006612f1f565b611ab27f31000000000000000000000000000000000000000000000000000000000000016007612f1f565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b60606005805461068890614e13565b3360008181526002602090815260408083206001600160a01b038716845290915281205490919083811015611b755760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084015b60405180910390fd5b610a8f82868684036120b5565b60003361071981858561284c565b611b986149a9565b50604080516060810182526001600160a01b037f000000000000000000000000dafff5445581906aec91f4b26d7f15351dd2964b811682527f0000000000000000000000006fd9581e71786a4fe3f533b3c64c896c6c186231811660208301527f00000000000000000000000079a5856906bdbf4e35e108e5f396b6b117204857169181019190915290565b336001600160a01b03167f00000000000000000000000017354e8e7518599c7f6b7095a6706766e4e4dc616001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611c8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cb09190614fa7565b6001600160a01b031614611cd757604051630bcaf99960e21b815260040160405180910390fd5b816c1b1b91995954985d19549bdbdd609a1b03611d3b5766ad566553da1bb7811115611d1657604051633efe7b6f60e01b815260040160405180910390fd5b600a805469ffffffffffffffffffff191669ffffffffffffffffffff83161790555050565b817f70726f746f636f6c46656550657263656e74000000000000000000000000000003611da7576064811115611d8457604051630329b03560e11b815260040160405180910390fd5b600a80546aff000000000000000000001916600160501b60ff8416021790555050565b604051636d4eea9360e11b815260040160405180910390fd5b83421115611e105760405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606401611b6c565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9888888611e3f8c612fca565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090506000611e9a82612ff2565b90506000611eaa8287878761301f565b9050896001600160a01b0316816001600160a01b031614611f0d5760405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152606401611b6c565b611f188a8a8a6120b5565b50505050505050505050565b600080611f2f6121d9565b30600090815260016020526040902054600c546001600160801b03600160801b820481169116611f60828285613047565b909550935084158015611f71575083155b15611f8f576040516354353b2760e01b815260040160405180910390fd5b611f9c61181f8684614e5d565b600c80546001600160801b03928316600160801b029216919091179055611fc661181f8583614e5d565b600c80546fffffffffffffffffffffffffffffffff19166001600160801b03929092169190911790556120237f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031687876122fa565b6120576001600160a01b037f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde1687866122fa565b60408051848152602081018790529081018590526001600160a01b038716907f743033787f4738ff4d6a7225ce2bd0977ee5f86b91a902a58f5e4d0b297b46449060600160405180910390a25050506120b06001600055565b915091565b6001600160a01b0383166121175760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401611b6c565b6001600160a01b0382166121785760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401611b6c565b6001600160a01b0383811660008181526002602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b60026000540361222b5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401611b6c565b6002600055565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b1790529051600091829182916001600160a01b038616916122899190614fc4565b600060405180830381855afa9150503d80600081146122c4576040519150601f19603f3d011682016040523d82523d6000602084013e6122c9565b606091505b50915091508180156122dd57506020815110155b6122e657600080fd5b80806020019051810190611a2d9190614ec6565b6040516001600160a01b03831660248201526044810182905261237590849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03167fffffffff00000000000000000000000000000000000000000000000000000000909316929092179091526130b9565b505050565b6123c260405180610100016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b60007f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde6001600160a01b031663bb7b8b806040518163ffffffff1660e01b8152600401602060405180830381865afa158015612422573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124469190614ec6565b604080516101008101909152600c54919250908190670de0b6b3a764000090849061247c906003906001600160801b0316614fe0565b6124869190614fe0565b612490919061500d565b8152600c546020909101906124d590600160801b90046001600160801b03167f000000000000000000000000000000000000000000000000000000000000001261318e565b815260208101929092527f000000000000000000000000000000000000000000000004d2c3d7905734ee0060408301527f00000000000000000000000000000000000000000000000000000000677243556060830152600a5469ffffffffffffffffffff81166080840152600160501b900460ff1660a0830152600b5460c090920191909152919050565b6000806000806000806125948861258f61258a8a60038d604001516125859190614fe0565b6131b0565b6127a9565b6131c5565b9250925092506125a38361322a565b95506125ae8261322a565b94506125b98161322a565b93505050509250925092565b60006125d2826012615021565b6125dd90600a61511e565b6125e7908461500d565b9392505050565b60e0810151600b5560408101516126299061260a906003614fe0565b825161261f90670de0b6b3a764000090614fe0565b61181f919061500d565b600c80546fffffffffffffffffffffffffffffffff19166001600160801b039290921691909117905560208101516126859061181f907f00000000000000000000000000000000000000000000000000000000000000126125c5565b600c80546001600160801b03928316600160801b02921691909117905560e08101516040517f03209b52f068a7fc82f5defd3aff047085d3503077b90e6b018b83a90c140856916126d99190815260200190565b60405180910390a150565b6040516001600160a01b038085166024830152831660448201526064810182905261271c9085906323b872dd60e01b90608401612326565b50505050565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8211156127a55760405162461bcd60e51b815260206004820152602860248201527f53616665436173743a2076616c756520646f65736e27742066697420696e2061604482015267371034b73a191a9b60c11b6064820152608401611b6c565b5090565b60006127b482612722565b61071f9060001961512d565b6001600160a01b03838116600090815260026020908152604080832093861683529290522054600019811461271c578181101561283f5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401611b6c565b61271c84848484036120b5565b6001600160a01b0383166128b05760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401611b6c565b6001600160a01b0382166129125760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401611b6c565b6001600160a01b0383166000908152600160205260409020548181101561298a5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401611b6c565b6001600160a01b0380851660008181526001602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906129ea9086815260200190565b60405180910390a361271c565b6000306001600160a01b037f0000000000000000000000005a2d321ed5c525e52a3b8d295c6d097a3c78b82116148015612a5057507f000000000000000000000000000000000000000000000000000000000000000146145b15612a7a57507f98328885f9eb90c6badc11d9f750b5b0a0749133164ef68c3b7d075e4fcf2ce390565b610aea604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f7aac0d2e56122277a4fd2423d07dc97e1dc845ee88115e7c227f86e3923ada2a918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b600080600080600080612b518861258f612b4c8a60038d60400151612b479190614fe0565b61327c565b612722565b9250925092506125a3612b6384613291565b61322a565b600080600080612b7760035490565b905080600003612db4576103e8612bc186612bb2897f000000000000000000000000000000000000000000000000000000000000001261318e565b612bbc9190614fe0565b61329f565b612bcb9190614e5d565b935085925084915060007f000000000000000000000000f7e009b8111c09a906d1d84938745b9edeedfdde6001600160a01b031663bb7b8b806040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c33573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c579190614ec6565b9050612c6660016103e8613387565b612d76604051806101000160405280670de0b6b3a764000084600388612c8c9190614fe0565b612c969190614fe0565b612ca0919061500d565b8152602001612ccf877f000000000000000000000000000000000000000000000000000000000000001261318e565b8152602081018490527f000000000000000000000000000000000000000000000004d2c3d7905734ee0060408201527f00000000000000000000000000000000000000000000000000000000677243556060820152600a5469ffffffffffffffffffff81166080830152600160501b900460ff1660a0820152600060c0909101527f0000000000000000000000000000000000000000000000000e3872be3bd5ae00613448565b600b8190556040519081527f03209b52f068a7fc82f5defd3aff047085d3503077b90e6b018b83a90c1408569060200160405180910390a150612e33565b600088612dc18388614fe0565b612dcb919061500d565b905060008a612dda848a614fe0565b612de4919061500d565b905080821015612e125781955086935082868c612e019190614fe0565b612e0b919061500d565b9450612e30565b94508693508482612e23828c614fe0565b612e2d919061500d565b93505b50505b83600003612e54576040516354353b2760e01b815260040160405180910390fd5b612e5e8785613387565b60408051858152602081018590529081018390526001600160a01b038816907fb4c03061fb5b7fed76389d5af8f2e0ddb09f8c70d1333abbb62582835e10accb9060600160405180910390a250955095509592505050565b60006001600160801b038211156127a55760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b6064820152608401611b6c565b606060ff8314612f3957612f3283613480565b905061071f565b818054612f4590614e13565b80601f0160208091040260200160405190810160405280929190818152602001828054612f7190614e13565b8015612fbe5780601f10612f9357610100808354040283529160200191612fbe565b820191906000526020600020905b815481529060010190602001808311612fa157829003601f168201915b5050505050905061071f565b6001600160a01b03811660009081526008602052604090208054600181018255905b50919050565b600061071f612fff6129f7565b8360405161190160f01b8152600281019290925260228201526042902090565b6000806000613030878787876134bf565b9150915061303d81613583565b5095945050505050565b6000808260000361306b57604051634f3f1ff560e11b815260040160405180910390fd5b600061307660035490565b9050806130838786614fe0565b61308d919061500d565b92508061309a8686614fe0565b6130a4919061500d565b91506130b030856136d0565b50935093915050565b600061310e826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166138049092919063ffffffff16565b905080516000148061312f57508080602001905181019061312f9190614edf565b6123755760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401611b6c565b600061319b826012615021565b6131a690600a61511e565b6125e79084614fe0565b60006125e78383670de0b6b3a7640000613813565b6000806000836131d88660000151612722565b136131f657604051634d7393f160e11b815260040160405180910390fd5b600061320186613831565b905061320e8682876138ab565b9195509350915061322286828787866139dc565b509250925092565b6000808212156127a55760405162461bcd60e51b815260206004820181905260248201527f53616665436173743a2076616c7565206d75737420626520706f7369746976656044820152606401611b6c565b60006125e78383670de0b6b3a7640000613a82565b600061071f8260001961512d565b6000816000036132b157506000919050565b600060016132be84613aa8565b901c6001901b905060018184816132d7576132d7614ff7565b048201901c905060018184816132ef576132ef614ff7565b048201901c9050600181848161330757613307614ff7565b048201901c9050600181848161331f5761331f614ff7565b048201901c9050600181848161333757613337614ff7565b048201901c9050600181848161334f5761334f614ff7565b048201901c9050600181848161336757613367614ff7565b048201901c90506125e78182858161338157613381614ff7565b04613b3c565b6001600160a01b0382166133dd5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401611b6c565b80600360008282546133ef9190614f59565b90915550506001600160a01b0382166000818152600160209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b60008042846080015161345b9190614e5d565b905060006134698583613b52565b905061101185600001518660200151838786613baa565b6060600061348d83613c03565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311156134f6575060009050600361357a565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa15801561354a573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166135735760006001925092505061357a565b9150600090505b94509492505050565b60008160048111156135975761359761515d565b0361359f5750565b60018160048111156135b3576135b361515d565b036136005760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401611b6c565b60028160048111156136145761361461515d565b036136615760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401611b6c565b60038160048111156136755761367561515d565b036136cd5760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401611b6c565b50565b6001600160a01b0382166137305760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401611b6c565b6001600160a01b038216600090815260016020526040902054818110156137a45760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401611b6c565b6001600160a01b03831660008181526001602090815260408083208686039055600380548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6060611a2d8484600085613c2b565b600082600019048411830215820261382a57600080fd5b5091020490565b61385560405180606001604052806000815260200160008152602001600081525090565b60004283608001516138679190614e5d565b90506138738382613b52565b808352835160e0850151602086015161388c9385613d06565b602083015260a08301516138a09082613d70565b604083015250919050565b6000806000806138d1612b4c8860000151896020015189600001518a602001518a613da7565b905060006138e76138e28784613e63565b613291565b905060008087131561396457600061390c896040015185613e6390919063ffffffff16565b9050670de0b6b3a764000081121561393a57604051631586184160e31b815260048101829052602401611b6c565b61395c8960400151670de0b6b3a76400006139559190615173565b8490613e78565b915050613996565b60408801516139939061397f81670de0b6b3a7640000615173565b613989908561512d565b6138e2919061519a565b90505b60006139a28284615173565b9050600060646139b58c60c00151612722565b6139bf908561512d565b6139c9919061519a565b919b929a50909850909650505050505050565b6139f7836139ed8760000151612722565b612b639190615173565b8552613a1c612b63613a0983856151c8565b613a168860200151612722565b90613e8d565b60208601526080850151600090613a34904290614e5d565b9050613a53866000015187602001518760000151886020015185613baa565b60e08701819052600003613a7a57604051634800fe7f60e01b815260040160405180910390fd5b505050505050565b6000826000190484118302158202613a9957600080fd5b50910281810615159190040190565b600080608083901c15613abd57608092831c92015b604083901c15613acf57604092831c92015b602083901c15613ae157602092831c92015b601083901c15613af357601092831c92015b600883901c15613b0557600892831c92015b600483901c15613b1757600492831c92015b600283901c15613b2957600292831c92015b600183901c1561071f5760010192915050565b6000818310613b4b57816125e7565b5090919050565b60008082613b656201518061016d614fe0565b8560600151613b749190614fe0565b613b7e919061500d565b905080600003613ba15760405163117aed9560e21b815260040160405180910390fd5b611a2d81612722565b600080613bbe612b4c888888886000613da7565b90506000613bd1613bce83613ed4565b90565b905083613be36201518061016d614fe0565b613bed9083614fe0565b613bf7919061500d565b98975050505050505050565b600060ff8216601f81111561071f57604051632cd44ac360e21b815260040160405180910390fd5b606082471015613c8c5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401611b6c565b600080866001600160a01b03168587604051613ca89190614fc4565b60006040518083038185875af1925050503d8060008114613ce5576040519150601f19603f3d011682016040523d82523d6000602084013e613cea565b606091505b5091509150613cfb87838387613f0b565b979650505050505050565b600080613d138684613d70565b9050670de0b6b3a7640000811215613d2a57600080fd5b6000613d40613d39878a614f59565b8990613f84565b90506000613d4d82613f99565b9050613d598187613e63565b613d639084615173565b9998505050505050505050565b600080613d826201518061016d614fe0565b613d8c8486614fe0565b613d96919061500d565b9050611a2d612b4c613bce83613ff2565b600080613db7836139ed89612722565b90506000613dcf613dc8888a614f59565b8390613f84565b9050670d529ae9e8600000811115613dfa57604051635677eea360e01b815260040160405180910390fd5b6000613e0582613f99565b9050600086613e14838a613e63565b613e1e91906151c8565b9050670de0b6b3a7640000811215613e4c57604051631586184160e31b815260048101829052602401611b6c565b613e558161322a565b9a9950505050505050505050565b60006125e783670de0b6b3a764000084614040565b60006125e78383670de0b6b3a7640000614040565b600081831215613eca5760405162461bcd60e51b81526020600482015260086024820152676e6567617469766560c01b6044820152606401611b6c565b6125e78284615173565b600061071f6714057b7ef767814f670de0b6b3a7640000613ef7613bce86614068565b613f01919061512d565b613bce919061519a565b60608315613f7a578251600003613f73576001600160a01b0385163b613f735760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401611b6c565b5081611a2d565b611a2d83836141ce565b60006125e783670de0b6b3a764000084613813565b6000670de0b6b3a76400008203613fc357604051631b65cfed60e31b815260040160405180910390fd5b6000613fe4612b4c613fdd85670de0b6b3a7640000614e5d565b8590613f84565b90506125e7613bce82613ed4565b600081680736ea4425c11ac63081111561402257604051630d7b1d6560e11b815260048101849052602401611b6c565b6714057b7ef767814f8102611a2d670de0b6b3a764000082046141f8565b60008061404d848661512d565b905082818161405e5761405e614ff7565b0595945050505050565b60008181811361408e5760405163059b101b60e01b815260048101849052602401611b6c565b6000670de0b6b3a764000082126140a7575060016140cd565b50600019816ec097ce7bc90715b34b9f1000000000816140c9576140c9614ff7565b0591505b6000614150670de0b6b3a7640000840560016001600160801b03821160071b91821c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211871b91821c969096119490961792909217171791909117919091171790565b9050670de0b6b3a7640000810283821d670de0b6b3a763ffff19810161417d575091909102949350505050565b671bc16d674ec800006706f05b59d3b200005b60008113156141c357670de0b6b3a76400008380020592508183126141bb579283019260019290921d915b60011d614190565b509184029182613bf7565b8151156141de5781518083602001fd5b8060405162461bcd60e51b8152600401611b6c9190614a17565b600081680a688906bd8affffff8111156142285760405163b3b6ba1f60e01b815260048101849052602401611b6c565b6000614240670de0b6b3a7640000604084901b61500d565b9050611a2d613bce82600160bf1b67ff000000000000008216156143565767800000000000000082161561427d5768016a09e667f3bcc9090260401c5b67400000000000000082161561429c576801306fe0a31b7152df0260401c5b6720000000000000008216156142bb576801172b83c7d517adce0260401c5b6710000000000000008216156142da5768010b5586cf9890f62a0260401c5b6708000000000000008216156142f9576801059b0d31585743ae0260401c5b67040000000000000082161561431857680102c9a3e778060ee70260401c5b6702000000000000008216156143375768010163da9fb33356d80260401c5b67010000000000000082161561435657680100b1afa5abcbed610260401c5b66ff0000000000008216156144555766800000000000008216156143835768010058c86da1c09ea20260401c5b66400000000000008216156143a1576801002c605e2e8cec500260401c5b66200000000000008216156143bf57680100162f3904051fa10260401c5b66100000000000008216156143dd576801000b175effdc76ba0260401c5b66080000000000008216156143fb57680100058ba01fb9f96d0260401c5b66040000000000008216156144195768010002c5cc37da94920260401c5b6602000000000000821615614437576801000162e525ee05470260401c5b66010000000000008216156144555768010000b17255775c040260401c5b65ff000000000082161561454b5765800000000000821615614480576801000058b91b5bc9ae0260401c5b6540000000000082161561449d57680100002c5c89d5ec6d0260401c5b652000000000008216156144ba5768010000162e43f4f8310260401c5b651000000000008216156144d757680100000b1721bcfc9a0260401c5b650800000000008216156144f45768010000058b90cf1e6e0260401c5b65040000000000821615614511576801000002c5c863b73f0260401c5b6502000000000082161561452e57680100000162e430e5a20260401c5b6501000000000082161561454b576801000000b1721835510260401c5b64ff000000008216156146385764800000000082161561457457680100000058b90c0b490260401c5b6440000000008216156145905768010000002c5c8601cc0260401c5b6420000000008216156145ac576801000000162e42fff00260401c5b6410000000008216156145c85768010000000b17217fbb0260401c5b6408000000008216156145e4576801000000058b90bfce0260401c5b64040000000082161561460057680100000002c5c85fe30260401c5b64020000000082161561461c5768010000000162e42ff10260401c5b64010000000082161561463857680100000000b17217f80260401c5b63ff00000082161561471c57638000000082161561465f5768010000000058b90bfc0260401c5b634000000082161561467a576801000000002c5c85fe0260401c5b632000000082161561469557680100000000162e42ff0260401c5b63100000008216156146b0576801000000000b17217f0260401c5b63080000008216156146cb57680100000000058b90c00260401c5b63040000008216156146e65768010000000002c5c8600260401c5b6302000000821615614701576801000000000162e4300260401c5b630100000082161561471c5768010000000000b172180260401c5b62ff00008216156147f75762800000821615614741576801000000000058b90c0260401c5b6240000082161561475b57680100000000002c5c860260401c5b622000008216156147755768010000000000162e430260401c5b6210000082161561478f57680100000000000b17210260401c5b620800008216156147a95768010000000000058b910260401c5b620400008216156147c3576801000000000002c5c80260401c5b620200008216156147dd57680100000000000162e40260401c5b620100008216156147f7576801000000000000b1720260401c5b61ff008216156148c95761800082161561481a57680100000000000058b90260401c5b6140008216156148335768010000000000002c5d0260401c5b61200082161561484c576801000000000000162e0260401c5b6110008216156148655768010000000000000b170260401c5b61080082161561487e576801000000000000058c0260401c5b61040082161561489757680100000000000002c60260401c5b6102008216156148b057680100000000000001630260401c5b6101008216156148c957680100000000000000b10260401c5b60ff8216156149925760808216156148ea57680100000000000000590260401c5b6040821615614902576801000000000000002c0260401c5b602082161561491a57680100000000000000160260401c5b6010821615614932576801000000000000000b0260401c5b600882161561494a57680100000000000000060260401c5b600482161561496257680100000000000000030260401c5b600282161561497a57680100000000000000010260401c5b600182161561499257680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b60405180606001604052806003906020820280368337509192915050565b60005b838110156149e25781810151838201526020016149ca565b50506000910152565b60008151808452614a038160208601602086016149c7565b601f01601f19169290920160200192915050565b6020815260006125e760208301846149eb565b6001600160a01b03811681146136cd57600080fd5b60008060408385031215614a5257600080fd5b8235614a5d81614a2a565b946020939093013593505050565b60008060408385031215614a7e57600080fd5b823591506020830135614a9081614a2a565b809150509250929050565b600080600060608486031215614ab057600080fd5b8335614abb81614a2a565b92506020840135614acb81614a2a565b929592945050506040919091013590565b600080600080600060808688031215614af457600080fd5b85359450602086013593506040860135614b0d81614a2a565b9250606086013567ffffffffffffffff80821115614b2a57600080fd5b818801915088601f830112614b3e57600080fd5b813581811115614b4d57600080fd5b896020828501011115614b5f57600080fd5b9699959850939650602001949392505050565b634e487b7160e01b600052604160045260246000fd5b60008060008060808587031215614b9e57600080fd5b84359350602085013592506040850135614bb781614a2a565b9150606085013567ffffffffffffffff80821115614bd457600080fd5b818701915087601f830112614be857600080fd5b813581811115614bfa57614bfa614b72565b604051601f8201601f19908116603f01168101908382118183101715614c2257614c22614b72565b816040528281528a6020848701011115614c3b57600080fd5b82602086016020830137600060208483010152809550505050505092959194509250565b600060208284031215614c7157600080fd5b81356125e781614a2a565b60ff60f81b881681526000602060e081840152614c9c60e084018a6149eb565b8381036040850152614cae818a6149eb565b606085018990526001600160a01b038816608086015260a0850187905284810360c0860152855180825283870192509083019060005b81811015614d0057835183529284019291840191600101614ce4565b50909c9b505050505050505050505050565b60608101818360005b6003811015614d435781516001600160a01b0316835260209283019290910190600101614d1b565b50505092915050565b60008060408385031215614d5f57600080fd5b50508035926020909101359150565b600080600080600080600060e0888a031215614d8957600080fd5b8735614d9481614a2a565b96506020880135614da481614a2a565b95506040880135945060608801359350608088013560ff81168114614dc857600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215614df857600080fd5b8235614e0381614a2a565b91506020830135614a9081614a2a565b600181811c90821680614e2757607f821691505b602082108103612fec57634e487b7160e01b600052602260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8181038181111561071f5761071f614e47565b634e487b7160e01b600052603260045260246000fd5b8060005b600381101561271c578151845260209384019390910190600101614e8a565b60808101614eb78285614e86565b82151560608301529392505050565b600060208284031215614ed857600080fd5b5051919050565b600060208284031215614ef157600080fd5b815180151581146125e757600080fd5b84815283602082015260606040820152816060820152818360808301376000818301608090810191909152601f909201601f191601019392505050565b60808101614f4c8285614e86565b8260608301529392505050565b8082018082111561071f5761071f614e47565b6000600160ff1b8201614f8157614f81614e47565b5060000390565b83815282602082015260606040820152600061101160608301846149eb565b600060208284031215614fb957600080fd5b81516125e781614a2a565b60008251614fd68184602087016149c7565b9190910192915050565b808202811582820484141761071f5761071f614e47565b634e487b7160e01b600052601260045260246000fd5b60008261501c5761501c614ff7565b500490565b60ff828116828216039081111561071f5761071f614e47565b600181815b8085111561507557816000190482111561505b5761505b614e47565b8085161561506857918102915b93841c939080029061503f565b509250929050565b60008261508c5750600161071f565b816150995750600061071f565b81600181146150af57600281146150b9576150d5565b600191505061071f565b60ff8411156150ca576150ca614e47565b50506001821b61071f565b5060208310610133831016604e8410600b84101617156150f8575081810a61071f565b615102838361503a565b806000190482111561511657615116614e47565b029392505050565b60006125e760ff84168361507d565b80820260008212600160ff1b8414161561514957615149614e47565b818105831482151761071f5761071f614e47565b634e487b7160e01b600052602160045260246000fd5b818103600083128015838313168383128216171561519357615193614e47565b5092915050565b6000826151a9576151a9614ff7565b600160ff1b8214600019841416156151c3576151c3614e47565b500590565b80820182811260008312801582168215821617156151e8576151e8614e47565b50509291505056fea164736f6c6343000813000a
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.