ERC-20
Overview
Max Total Supply
13.112071005941525697 pWETH
Holders
41
Total Transfers
-
Market
Price
$0.00 @ 0.000000 ETH
Onchain Market Cap
$0.00
Circulating Supply Market Cap
-
Other Info
Token Contract (WITH 18 Decimals)
Loading...
Loading
Loading...
Loading
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x77935F2c...aa283906B The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
VaultV2
Compiler Version
v0.8.19+commit.7dd6d404
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { ERC20, IERC20, IERC20Metadata } from "openzeppelin/token/ERC20/ERC20.sol"; import { IERC4626 } from "openzeppelin/interfaces/IERC4626.sol"; import { ERC20Permit, IERC20Permit } from "openzeppelin/token/ERC20/extensions/ERC20Permit.sol"; import { SafeERC20 } from "openzeppelin/token/ERC20/utils/SafeERC20.sol"; import { SafeCast } from "openzeppelin/utils/math/SafeCast.sol"; import { Math } from "openzeppelin/utils/math/Math.sol"; import { Ownable } from "owner-manager-contracts/Ownable.sol"; import { ILiquidationSource } from "pt-v5-liquidator-interfaces/ILiquidationSource.sol"; import { PrizePool } from "pt-v5-prize-pool/PrizePool.sol"; import { TwabController, SPONSORSHIP_ADDRESS } from "pt-v5-twab-controller/TwabController.sol"; import { IClaimable } from "pt-v5-claimable-interface/interfaces/IClaimable.sol"; import { VaultHooks } from "./interfaces/IVaultHooks.sol"; /** * @title PoolTogether V5 Vault (Version 2) * @author PoolTogether Inc. & G9 Software Inc. * @notice Vault extends the ERC4626 standard and is the entry point for users interacting with a V5 pool. * Users deposit an underlying asset (i.e. USDC) in this contract and receive in exchange an ERC20 token * representing their share of deposit in the vault. * Underlying assets are then deposited in a YieldVault to generate yield. * This yield is sold for prize tokens (i.e. POOL) via the Liquidator and captured by the PrizePool to be awarded to depositors. * @dev Balances are stored in the TwabController contract. */ contract VaultV2 is IERC4626, ERC20Permit, ILiquidationSource, IClaimable, Ownable { using Math for uint256; using SafeCast for uint256; using SafeERC20 for IERC20; /* ============ Variables ============ */ /// The maximum amount of shares that can be minted. uint256 private constant UINT96_MAX = type(uint96).max; /// @notice Address of the underlying asset used by the Vault. IERC20 private immutable _asset; /// @notice Underlying asset decimals. uint8 private immutable _underlyingDecimals; /// @notice Fee precision denominated in 9 decimal places and used to calculate yield fee percentage. uint32 private constant FEE_PRECISION = 1e9; /// @notice Yield fee percentage represented in integer format with 9 decimal places (i.e. 10000000 = 0.01 = 1%). uint32 private _yieldFeePercentage; /// @notice The gas to give to each of the before and after prize claim hooks. /// This should be enough gas to mint an NFT if needed. uint24 private constant HOOK_GAS = 150_000; /// @notice Address of the TwabController used to keep track of balances. TwabController private immutable _twabController; /// @notice Address of the ERC4626 vault generating yield. IERC4626 private immutable _yieldVault; /// @notice Address of the PrizePool that computes prizes. PrizePool private immutable _prizePool; /// @notice Address of the claimer. address private _claimer; /// @notice Address of the liquidation pair used to liquidate yield for prize token. address private _liquidationPair; /// @notice Address of the yield fee recipient. Receives Vault shares when `mintYieldFee` is called. address private _yieldFeeRecipient; /// @notice Total yield fee shares available. Can be minted to `_yieldFeeRecipient` by calling `mintYieldFee`. uint256 private _yieldFeeShares; /// @notice Maps user addresses to hooks that they want to execute when prizes are won. mapping(address => VaultHooks) internal _hooks; /* ============ Events ============ */ /** * @notice Emitted when a new Vault has been deployed. * @param asset Address of the underlying asset used by the vault * @param name Name of the ERC20 share minted by the vault * @param symbol Symbol of the ERC20 share minted by the vault * @param twabController Address of the TwabController used to keep track of balances * @param yieldVault Address of the ERC4626 vault in which assets are deposited to generate yield * @param prizePool Address of the PrizePool that computes prizes * @param claimer Address of the claimer * @param yieldFeeRecipient Address of the yield fee recipient * @param yieldFeePercentage Yield fee percentage in integer format with 1e9 precision (50% would be 5e8) * @param owner Address of the contract owner */ event NewVault( IERC20 indexed asset, string name, string symbol, TwabController twabController, IERC4626 indexed yieldVault, PrizePool indexed prizePool, address claimer, address yieldFeeRecipient, uint256 yieldFeePercentage, address owner ); /** * @notice Emitted when an account sets new hooks * @param account The account whose hooks are being configured * @param hooks The hooks being set */ event SetHooks(address indexed account, VaultHooks indexed hooks); /** * @notice Emitted when yield fee is minted to the yield recipient. * @param caller Address that called the function * @param recipient Address receiving the Vault shares * @param shares Amount of shares minted to `recipient` */ event MintYieldFee(address indexed caller, address indexed recipient, uint256 shares); /** * @notice Emitted when a new yield fee recipient has been set. * @param yieldFeeRecipient Address of the new yield fee recipient */ event YieldFeeRecipientSet(address indexed yieldFeeRecipient); /** * @notice Emitted when a new yield fee percentage has been set. * @param yieldFeePercentage New yield fee percentage */ event YieldFeePercentageSet(uint256 yieldFeePercentage); /** * @notice Emitted when a user sponsors the Vault. * @param caller Address that called the function * @param assets Amount of assets deposited into the Vault * @param shares Amount of shares minted to the caller address */ event Sponsor(address indexed caller, uint256 assets, uint256 shares); /** * @notice Emitted when a user sweeps assets held by the Vault into the YieldVault. * @param caller Address that called the function * @param assets Amount of assets sweeped into the YieldVault */ event Sweep(address indexed caller, uint256 assets); /* ============ Errors ============ */ /// @notice Emitted when the Yield Vault is set to the zero address. error YieldVaultZeroAddress(); /// @notice Emitted when the Prize Pool is set to the zero address. error PrizePoolZeroAddress(); /// @notice Emitted when the Owner is set to the zero address. error OwnerZeroAddress(); /** * @notice Emitted when the underlying asset passed to the constructor is different from the YieldVault one. * @param asset Address of the underlying asset passed to the constructor * @param yieldVaultAsset Address of the YieldVault underlying asset */ error UnderlyingAssetMismatch(address asset, address yieldVaultAsset); /** * @notice Emitted when the amount being deposited for the receiver is greater than the max amount allowed. * @param receiver The receiver of the deposit * @param amount The amount to deposit * @param max The max deposit amount allowed */ error DepositMoreThanMax(address receiver, uint256 amount, uint256 max); /** * @notice Emitted when the amount being minted for the receiver is greater than the max amount allowed. * @param receiver The receiver of the mint * @param amount The amount to mint * @param max The max mint amount allowed */ error MintMoreThanMax(address receiver, uint256 amount, uint256 max); /** * @notice Emitted when the amount being withdrawn for the owner is greater than the max amount allowed. * @param owner The owner of the assets * @param amount The amount to withdraw * @param max The max withdrawable amount */ error WithdrawMoreThanMax(address owner, uint256 amount, uint256 max); /** * @notice Emitted when the amount being redeemed for owner is greater than the max allowed amount. * @param owner The owner of the assets * @param amount The amount to redeem * @param max The max redeemable amount */ error RedeemMoreThanMax(address owner, uint256 amount, uint256 max); /// @notice Emitted when `_deposit` is called but no shares are minted back to the receiver. error MintZeroShares(); /// @notice Emitted when `_withdraw` is called but no assets are being withdrawn. error WithdrawZeroAssets(); /** * @notice Emitted when `_withdraw` is called but the amount of assets withdrawn from the YieldVault * is lower than the amount of assets requested by the caller. * @param requestedAssets The amount of assets requested * @param withdrawnAssets The amount of assets withdrawn from the YieldVault */ error WithdrawAssetsLTRequested(uint256 requestedAssets, uint256 withdrawnAssets); /// @notice Emitted when `sweep` is called but no underlying assets are currently held by the Vault. error SweepZeroAssets(); /** * @notice Emitted during the liquidation process when the caller is not the liquidation pair contract. * @param caller The caller address * @param liquidationPair The LP address */ error CallerNotLP(address caller, address liquidationPair); /** * @notice Emitted during the liquidation process when the token in is not the prize token. * @param tokenIn The provided tokenIn address * @param prizeToken The prize token address */ error LiquidationTokenInNotPrizeToken(address tokenIn, address prizeToken); /** * @notice Emitted during the liquidation process when the token out is not the vault share token. * @param tokenOut The provided tokenOut address * @param vaultShare The vault share token address */ error LiquidationTokenOutNotVaultShare(address tokenOut, address vaultShare); /// @notice Emitted during the liquidation process when the liquidation amount out is zero. error LiquidationAmountOutZero(); /** * @notice Emitted during the liquidation process if the amount out is greater than the available yield. * @param amountOut The amount out * @param availableYield The available yield */ error LiquidationAmountOutGTYield(uint256 amountOut, uint256 availableYield); /// @notice Emitted when the Vault is under-collateralized. error VaultUndercollateralized(); /** * @notice Emitted when the target token is not supported for a given token address. * @param token The unsupported token address */ error TargetTokenNotSupported(address token); /// @notice Emitted when the Claimer is set to the zero address. error ClaimerZeroAddress(); /** * @notice Emitted when the caller is not the prize claimer. * @param caller The caller address * @param claimer The claimer address */ error CallerNotClaimer(address caller, address claimer); /** * @notice Emitted when the minted yield exceeds the yield fee shares available. * @param shares The amount of yield shares to mint * @param yieldFeeShares The accrued yield fee shares available */ error YieldFeeGTAvailableShares(uint256 shares, uint256 yieldFeeShares); /** * @notice Emitted when the minted yield exceeds the amount of available yield in the YieldVault. * @param shares The amount of yield shares to mint * @param availableYield The amount of yield available */ error YieldFeeGTAvailableYield(uint256 shares, uint256 availableYield); /// @notice Emitted when the Liquidation Pair being set is the zero address. error LPZeroAddress(); /** * @notice Emitted when the yield fee percentage being set is greater than or equal to 1. * @param yieldFeePercentage The yield fee percentage in integer format * @param maxYieldFeePercentage The max yield fee percentage in integer format (this value is equal to 1 in decimal format) */ error YieldFeePercentageGtePrecision(uint256 yieldFeePercentage, uint256 maxYieldFeePercentage); /** * @notice Emitted when the BeforeClaim prize hook fails * @param reason The revert reason that was thrown */ error BeforeClaimPrizeFailed(bytes reason); /** * @notice Emitted when the AfterClaim prize hook fails * @param reason The revert reason that was thrown */ error AfterClaimPrizeFailed(bytes reason); /// @notice Emitted when a prize is claimed for the zero address. error ClaimRecipientZeroAddress(); /** * @notice Emitted when the caller of a permit function is not the owner of the assets being permitted. * @param caller The address of the caller * @param owner The address of the owner */ error PermitCallerNotOwner(address caller, address owner); /** * @notice Emitted when a permit call on the underlying asset failed to set the spending allowance. * @dev This is likely thrown when the underlying asset does not support permit, but has a fallback function. * @param owner The owner of the assets * @param spender The spender of the assets * @param amount The amount of assets permitted * @param allowance The allowance after the permit was called */ error PermitAllowanceNotSet(address owner, address spender, uint256 amount, uint256 allowance); /* ============ Modifiers ============ */ /// @notice Modifier reverting if the Vault is under-collateralized. modifier onlyVaultCollateralized() { _onlyVaultCollateralized(_totalSupply(), _totalAssets()); _; } /** * @notice Reverts if the Vault is under-collateralized. * @param _depositedAssets Assets deposited into the YieldVault * @param _withdrawableAssets Assets withdrawable from the YieldVault */ function _onlyVaultCollateralized( uint256 _depositedAssets, uint256 _withdrawableAssets ) internal pure { if (!_isVaultCollateralized(_depositedAssets, _withdrawableAssets)) revert VaultUndercollateralized(); } /** * @notice Requires the caller to be the claimer. */ modifier onlyClaimer() { if (msg.sender != _claimer) revert CallerNotClaimer(msg.sender, _claimer); _; } /** * @notice Requires the caller to be the liquidation pair. */ modifier onlyLiquidationPair() { if (msg.sender != _liquidationPair) { revert CallerNotLP(msg.sender, _liquidationPair); } _; } /* ============ Constructor ============ */ /** * @notice Vault constructor * @dev `claimer_` can be set to address zero if none is available yet. * @param asset_ Address of the underlying asset used by the vault * @param name_ Name of the ERC20 share minted by the vault * @param symbol_ Symbol of the ERC20 share minted by the vault * @param yieldVault_ Address of the ERC4626 vault in which assets are deposited to generate yield * @param prizePool_ Address of the PrizePool that computes prizes * @param claimer_ Address of the claimer * @param yieldFeeRecipient_ Address of the yield fee recipient * @param yieldFeePercentage_ Yield fee percentage * @param owner_ Address that will gain ownership of this contract */ constructor( IERC20 asset_, string memory name_, string memory symbol_, IERC4626 yieldVault_, PrizePool prizePool_, address claimer_, address yieldFeeRecipient_, uint32 yieldFeePercentage_, address owner_ ) ERC20(name_, symbol_) ERC20Permit(name_) Ownable(owner_) { if (address(yieldVault_) == address(0)) revert YieldVaultZeroAddress(); if (address(prizePool_) == address(0)) revert PrizePoolZeroAddress(); if (owner_ == address(0)) revert OwnerZeroAddress(); if (address(asset_) != yieldVault_.asset()) { revert UnderlyingAssetMismatch(address(asset_), yieldVault_.asset()); } _setClaimer(claimer_); (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_); _underlyingDecimals = success ? assetDecimals : 18; _asset = asset_; TwabController twabController_ = prizePool_.twabController(); _twabController = twabController_; _yieldVault = yieldVault_; _prizePool = prizePool_; _setYieldFeeRecipient(yieldFeeRecipient_); _setYieldFeePercentage(yieldFeePercentage_); // Approve once for max amount asset_.safeIncreaseAllowance(address(yieldVault_), type(uint256).max); emit NewVault( asset_, name_, symbol_, twabController_, yieldVault_, prizePool_, claimer_, yieldFeeRecipient_, yieldFeePercentage_, owner_ ); } /* ===================================================== */ /* ============ Public & External Functions ============ */ /* ===================================================== */ /* ============ ERC20 / ERC4626 functions ============ */ /// @inheritdoc IERC4626 function asset() external view virtual override returns (address) { return address(_asset); } /// @inheritdoc ERC20 function balanceOf( address _account ) public view virtual override(ERC20, IERC20) returns (uint256) { return _balanceOf(_account); } /// @inheritdoc IERC20Metadata function decimals() public view virtual override(ERC20, IERC20Metadata) returns (uint8) { return _underlyingDecimals; } /// @inheritdoc IERC4626 function totalAssets() external view virtual override returns (uint256) { return _totalAssets(); } /// @inheritdoc ERC20 function totalSupply() public view virtual override(ERC20, IERC20) returns (uint256) { return _totalSupply(); } /* ============ Conversion Functions ============ */ /// @inheritdoc IERC4626 function convertToShares(uint256 _assets) external view virtual override returns (uint256) { return _convertToShares(_assets, _totalSupply(), _totalAssets(), Math.Rounding.Down); } /// @inheritdoc IERC4626 function convertToAssets(uint256 _shares) external view virtual override returns (uint256) { return _convertToAssets(_shares, _totalSupply(), _totalAssets(), Math.Rounding.Down); } /* ============ Max / Preview Functions ============ */ /// @inheritdoc IERC4626 function maxDeposit(address) external view virtual override returns (uint256) { uint256 _depositedAssets = _totalSupply(); return _isVaultCollateralized(_depositedAssets, _totalAssets()) ? _maxDeposit(_depositedAssets) : 0; } /// @inheritdoc IERC4626 function previewDeposit(uint256 _assets) external view virtual override returns (uint256) { return _convertToShares(_assets, _totalSupply(), _totalAssets(), Math.Rounding.Down); } /// @inheritdoc IERC4626 function maxMint(address) external view virtual override returns (uint256) { uint256 _depositedAssets = _totalSupply(); return _isVaultCollateralized(_depositedAssets, _totalAssets()) ? _maxDeposit(_depositedAssets) : 0; } /// @inheritdoc IERC4626 function previewMint(uint256 _shares) external view virtual override returns (uint256) { return _convertToAssets(_shares, _totalSupply(), _totalAssets(), Math.Rounding.Up); } /// @inheritdoc IERC4626 function maxWithdraw(address _owner) external view virtual override returns (uint256) { return _maxWithdraw(_owner); } /// @inheritdoc IERC4626 function previewWithdraw(uint256 _assets) external view virtual override returns (uint256) { return _convertToShares(_assets, _totalSupply(), _totalAssets(), Math.Rounding.Up); } /// @inheritdoc IERC4626 function maxRedeem(address _owner) external view virtual override returns (uint256) { return _maxRedeem(_owner); } /// @inheritdoc IERC4626 function previewRedeem(uint256 _shares) external view virtual override returns (uint256) { return _convertToAssets(_shares, _totalSupply(), _totalAssets(), Math.Rounding.Down); } /* ============ Deposit Functions ============ */ /** * @inheritdoc IERC4626 * @dev Will revert if the Vault is under-collateralized. */ function deposit(uint256 _assets, address _receiver) external virtual override returns (uint256) { return _depositAssets(_assets, msg.sender, _receiver, false); } /** * @notice Approve underlying asset with permit, deposit into the Vault and mint Vault shares to `_owner`. * @dev Can't be used to deposit on behalf of another user since `permit` does not accept a receiver parameter. * Meaning that anyone could reuse the signature and pass an arbitrary receiver to this function. * @dev Will revert if the Vault is under-collateralized. * @param _assets Amount of assets to approve and deposit * @param _owner Address of the owner depositing `_assets` and signing the permit * @param _deadline Timestamp after which the approval is no longer valid * @param _v V part of the secp256k1 signature * @param _r R part of the secp256k1 signature * @param _s S part of the secp256k1 signature * @return uint256 Amount of Vault shares minted to `_owner`. */ function depositWithPermit( uint256 _assets, address _owner, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external returns (uint256) { if (_owner != msg.sender) { revert PermitCallerNotOwner(msg.sender, _owner); } IERC20Permit(address(_asset)).permit(_owner, address(this), _assets, _deadline, _v, _r, _s); uint256 _allowance = _asset.allowance(_owner, address(this)); if (_allowance != _assets) { revert PermitAllowanceNotSet(_owner, address(this), _assets, _allowance); } return _depositAssets(_assets, _owner, _owner, false); } /** * @inheritdoc IERC4626 * @dev Will revert if the Vault is under-collateralized. */ function mint(uint256 _shares, address _receiver) external virtual override returns (uint256) { return _depositAssets(_shares, msg.sender, _receiver, true); } /** * @notice Deposit assets into the Vault and delegate to the sponsorship address. * @dev Will revert if the Vault is under-collateralized. * @param _assets Amount of assets to deposit * @return uint256 Amount of shares minted to caller. */ function sponsor(uint256 _assets) external returns (uint256) { address _owner = msg.sender; _depositAssets(_assets, _owner, _owner, false); if (_twabController.delegateOf(address(this), _owner) != SPONSORSHIP_ADDRESS) { _twabController.sponsor(_owner); } emit Sponsor(_owner, _assets, _assets); return _assets; } /** * @notice Deposit underlying assets that have been mistakenly sent to the Vault into the YieldVault. * @dev The deposited assets will contribute to the yield of the YieldVault. * @return uint256 Amount of underlying assets deposited */ function sweep() external returns (uint256) { uint256 _assets = _asset.balanceOf(address(this)); if (_assets == 0) revert SweepZeroAssets(); _yieldVault.deposit(_assets, address(this)); emit Sweep(msg.sender, _assets); return _assets; } /* ============ Withdraw Functions ============ */ /// @inheritdoc IERC4626 function withdraw( uint256 _assets, address _receiver, address _owner ) external virtual override returns (uint256) { if (_assets > _maxWithdraw(_owner)) { revert WithdrawMoreThanMax(_owner, _assets, _maxWithdraw(_owner)); } uint256 _depositedAssets = _totalSupply(); uint256 _withdrawableAssets = _totalAssets(); bool _vaultCollateralized = _isVaultCollateralized(_depositedAssets, _withdrawableAssets); uint256 _shares = _vaultCollateralized ? _assets : _convertToShares(_assets, _depositedAssets, _withdrawableAssets, Math.Rounding.Up); uint256 _withdrawnAssets = _redeem( msg.sender, _receiver, _owner, _shares, _assets, _vaultCollateralized ); if (_withdrawnAssets < _assets) revert WithdrawAssetsLTRequested(_assets, _withdrawnAssets); return _shares; } /// @inheritdoc IERC4626 function redeem( uint256 _shares, address _receiver, address _owner ) external virtual override returns (uint256) { if (_shares > _maxRedeem(_owner)) revert RedeemMoreThanMax(_owner, _shares, _maxRedeem(_owner)); uint256 _depositedAssets = _totalSupply(); uint256 _withdrawableAssets = _totalAssets(); bool _vaultCollateralized = _isVaultCollateralized(_depositedAssets, _withdrawableAssets); uint256 _assets = _convertToAssets( _shares, _depositedAssets, _withdrawableAssets, Math.Rounding.Down ); return _redeem(msg.sender, _receiver, _owner, _shares, _assets, _vaultCollateralized); } /* ============ Yield Functions ============ */ /** * @notice Total available yield amount accrued by this vault. * @return uint256 Total yield amount */ function availableYieldBalance() external view returns (uint256) { return _availableYieldBalance(); } /** * @notice Get the available yield fee amount accrued by this vault. * @return uint256 Yield fee amount */ function availableYieldFeeBalance() external view returns (uint256) { uint256 _availableYield = _availableYieldBalance(); if (_availableYield != 0 && _yieldFeePercentage != 0) { return _availableYieldFeeBalance(_availableYield); } return 0; } /** * @notice Mint Vault shares to the `_yieldFeeRecipient`. * @dev Will revert if the Vault is undercollateralized. * So shares does not need to be converted to assets. * @dev Will revert if `_shares` is greater than `_yieldFeeShares`. * @dev Will revert if there is not enough yield available in the YieldVault to back `_shares`. * @param _shares Amount of shares to mint */ function mintYieldFee(uint256 _shares) external { uint256 _depositedAssets = _totalSupply(); uint256 _withdrawableAssets = _totalAssets(); _onlyVaultCollateralized(_depositedAssets, _withdrawableAssets); uint256 _availableYield = _withdrawableAssets - _depositedAssets; if (_shares > _availableYield) revert YieldFeeGTAvailableYield(_shares, _availableYield); if (_shares > _yieldFeeShares) revert YieldFeeGTAvailableShares(_shares, _yieldFeeShares); address yieldFeeRecipient_ = _yieldFeeRecipient; _yieldFeeShares -= _shares; _mint(yieldFeeRecipient_, _shares); emit MintYieldFee(msg.sender, yieldFeeRecipient_, _shares); } /* ============ Liquidation Functions ============ */ /// @inheritdoc ILiquidationSource function liquidatableBalanceOf(address _token) external view override returns (uint256) { return _liquidatableBalanceOf(_token); } /** * @inheritdoc ILiquidationSource * @dev Will revert if the Vault is undercollateralized. * So `_amountOut` does not need to be converted to assets. * @dev User provides prize tokens and receives in exchange Vault shares. * @dev The yield fee can serve as a buffer in case of undercollateralization of the Vault. */ function transferTokensOut( address, address _receiver, address _tokenOut, uint256 _amountOut ) external virtual override onlyLiquidationPair onlyVaultCollateralized returns (bytes memory) { if (_tokenOut != address(this)) { revert LiquidationTokenOutNotVaultShare(_tokenOut, address(this)); } if (_amountOut == 0) revert LiquidationAmountOutZero(); uint256 _liquidatableYield = _liquidatableBalanceOf(_tokenOut); if (_amountOut > _liquidatableYield) { revert LiquidationAmountOutGTYield(_amountOut, _liquidatableYield); } // Distributes the specified yield fee percentage. // For instance, with a yield fee percentage of 20% and 8e18 Vault shares being liquidated, // this calculation assigns 2e18 Vault shares to the yield fee recipient. // `_amountOut` is the amount of Vault shares being liquidated after accounting for the yield fee. if (_yieldFeePercentage != 0) { _increaseYieldFeeBalance( (_amountOut * FEE_PRECISION) / (FEE_PRECISION - _yieldFeePercentage) - _amountOut ); } _mint(_receiver, _amountOut); return ""; } /** * @inheritdoc ILiquidationSource */ function verifyTokensIn( address _tokenIn, uint256 _amountIn, bytes calldata ) external virtual override onlyLiquidationPair { if (_tokenIn != address(_prizePool.prizeToken())) { revert LiquidationTokenInNotPrizeToken(_tokenIn, address(_prizePool.prizeToken())); } _prizePool.contributePrizeTokens(address(this), _amountIn); } /// @inheritdoc ILiquidationSource function targetOf(address) external view returns (address) { return address(_prizePool); } /// @inheritdoc ILiquidationSource function isLiquidationPair( address _tokenOut, address liquidationPair_ ) external view returns (bool) { return _tokenOut == address(this) && liquidationPair_ == _liquidationPair; } /* ============ Claim Functions ============ */ /** * @notice Claim prize for a winner * @param _winner The winner of the prize * @param _tier The prize tier * @param _prizeIndex The prize index * @param _fee The fee to charge * @param _feeRecipient The recipient of the fee * @return The total prize amount claimed. Zero if already claimed. */ function claimPrize( address _winner, uint8 _tier, uint32 _prizeIndex, uint96 _fee, address _feeRecipient ) external onlyClaimer returns (uint256) { VaultHooks memory hooks = _hooks[_winner]; address recipient; if (hooks.useBeforeClaimPrize) { try hooks.implementation.beforeClaimPrize{ gas: HOOK_GAS }( _winner, _tier, _prizeIndex, _fee, _feeRecipient ) returns (address result) { recipient = result; } catch (bytes memory reason) { revert BeforeClaimPrizeFailed(reason); } } else { recipient = _winner; } if (recipient == address(0)) revert ClaimRecipientZeroAddress(); uint256 prizeTotal = _prizePool.claimPrize( _winner, _tier, _prizeIndex, recipient, _fee, _feeRecipient ); if (hooks.useAfterClaimPrize) { try hooks.implementation.afterClaimPrize{ gas: HOOK_GAS }( _winner, _tier, _prizeIndex, prizeTotal, recipient ) {} catch (bytes memory reason) { revert AfterClaimPrizeFailed(reason); } } return prizeTotal; } /* ============ State Function ============ */ /** * @notice Check if the Vault is collateralized. * @return bool True if the vault is collateralized, false otherwise */ function isVaultCollateralized() external view returns (bool) { return _isVaultCollateralized(_totalSupply(), _totalAssets()); } /* ============ Setter Functions ============ */ /** * @notice Set claimer. * @param claimer_ Address of the claimer * @return address New claimer address */ function setClaimer(address claimer_) external onlyOwner returns (address) { _setClaimer(claimer_); emit ClaimerSet(claimer_); return claimer_; } /** * @notice Sets the hooks for a winner. * @param hooks The hooks to set */ function setHooks(VaultHooks calldata hooks) external { _hooks[msg.sender] = hooks; emit SetHooks(msg.sender, hooks); } /** * @notice Set liquidationPair. * @param liquidationPair_ New liquidationPair address * @return address New liquidationPair address */ function setLiquidationPair(address liquidationPair_) external onlyOwner returns (address) { if (address(liquidationPair_) == address(0)) revert LPZeroAddress(); _liquidationPair = liquidationPair_; emit LiquidationPairSet(address(this), address(liquidationPair_)); return address(liquidationPair_); } /** * @notice Set yield fee percentage. * @dev Yield fee is represented in 9 decimals and can't exceed `1e9`. * @param yieldFeePercentage_ Yield fee percentage * @return uint256 New yield fee percentage */ function setYieldFeePercentage(uint32 yieldFeePercentage_) external onlyOwner returns (uint256) { _setYieldFeePercentage(yieldFeePercentage_); emit YieldFeePercentageSet(yieldFeePercentage_); return yieldFeePercentage_; } /** * @notice Set fee recipient. * @param yieldFeeRecipient_ Address of the fee recipient * @return address New fee recipient address */ function setYieldFeeRecipient(address yieldFeeRecipient_) external onlyOwner returns (address) { _setYieldFeeRecipient(yieldFeeRecipient_); emit YieldFeeRecipientSet(yieldFeeRecipient_); return yieldFeeRecipient_; } /* ============ Getter Functions ============ */ /** * @notice Address of the yield fee recipient. * @return address Yield fee recipient address */ function yieldFeeRecipient() external view returns (address) { return _yieldFeeRecipient; } /** * @notice Yield fee percentage. * @return uint256 Yield fee percentage */ function yieldFeePercentage() external view returns (uint256) { return _yieldFeePercentage; } /** * @notice Get total yield fee accrued by this Vault. * @dev If the vault becomes undercollateralized, this total yield fee can be used to collateralize it. * @return uint256 Total accrued yield fee */ function yieldFeeShares() external view returns (uint256) { return _yieldFeeShares; } /** * @notice Address of the TwabController keeping track of balances. * @return address TwabController address */ function twabController() external view returns (address) { return address(_twabController); } /** * @notice Address of the ERC4626 vault generating yield. * @return address YieldVault address */ function yieldVault() external view returns (address) { return address(_yieldVault); } /** * @notice Address of the LiquidationPair used to liquidate yield for prize token. * @return address LiquidationPair address */ function liquidationPair() external view returns (address) { return _liquidationPair; } /** * @notice Address of the PrizePool that computes prizes. * @return address PrizePool address */ function prizePool() external view returns (address) { return address(_prizePool); } /// @inheritdoc IClaimable function claimer() external view returns (address) { return _claimer; } /** * @notice Gets the hooks for the given user. * @param _account The user to retrieve the hooks for * @return VaultHooks The hooks for the given user */ function getHooks(address _account) external view returns (VaultHooks memory) { return _hooks[_account]; } /* ============================================ */ /* ============ Internal Functions ============ */ /* ============================================ */ /* ============ ERC20 / ERC4626 functions ============ */ /** * @notice Fetch underlying asset decimals. * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way. * @param asset_ Address of the underlying asset * @return bool True if the attempt was successful, false otherwise * @return uint8 Token decimals number */ function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) { (bool success, bytes memory encodedDecimals) = address(asset_).staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (success && encodedDecimals.length >= 32) { uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256)); if (returnedDecimals <= type(uint8).max) { return (true, uint8(returnedDecimals)); } } return (false, 0); } /** * @notice Get the Vault shares balance of a given account. * @param _account Account to get the balance for * @return uint256 Balance of the account */ function _balanceOf(address _account) internal view returns (uint256) { return _twabController.balanceOf(address(this), _account); } /** * @notice Total amount of assets managed by this Vault. * @return uint256 Total amount of assets */ function _totalAssets() internal view returns (uint256) { return _yieldVault.maxWithdraw(address(this)); } /** * @notice Total amount of shares minted by this Vault. * @return uint256 Total amount of shares */ function _totalSupply() internal view returns (uint256) { return _twabController.totalSupply(address(this)); } /* ============ Conversion Functions ============ */ /** * @notice Convert assets to shares. * @param _assets Amount of assets to convert * @param _depositedAssets Assets deposited into the YieldVault * @param _withdrawableAssets Assets withdrawable from the YieldVault * @param _rounding Rounding mode (i.e. down or up) * @return uint256 Amount of shares corresponding to the assets */ function _convertToShares( uint256 _assets, uint256 _depositedAssets, uint256 _withdrawableAssets, Math.Rounding _rounding ) internal pure returns (uint256) { if (_assets == 0 || _depositedAssets == 0) { return _assets; } uint256 _collateralAssets = _collateral(_depositedAssets, _withdrawableAssets); return _collateralAssets == 0 ? 0 : _assets.mulDiv(_depositedAssets, _collateralAssets, _rounding); } /** * @notice Convert shares to assets. * @param _shares Amount of shares to convert * @param _depositedAssets Assets deposited into the YieldVault * @param _withdrawableAssets Assets withdrawable from the YieldVault * @param _rounding Rounding mode (i.e. down or up) * @return uint256 Amount of assets corresponding to the shares */ function _convertToAssets( uint256 _shares, uint256 _depositedAssets, uint256 _withdrawableAssets, Math.Rounding _rounding ) internal pure returns (uint256) { if (_shares == 0 || _depositedAssets == 0) { return _shares; } uint256 _collateralAssets = _collateral(_depositedAssets, _withdrawableAssets); return _collateralAssets == 0 ? 0 : _shares.mulDiv(_collateralAssets, _depositedAssets, _rounding); } /* ============ Max / Preview Functions ============ */ /** * @notice Returns the maximum amount of underlying assets that can be deposited into the Vault. * @dev We use type(uint96).max cause this is the type used to store balances in TwabController. * @param _depositedAssets Assets deposited into the YieldVault * @return uint256 Amount of underlying assets that can be deposited */ function _maxDeposit(uint256 _depositedAssets) internal view returns (uint256) { uint256 _vaultMaxDeposit = UINT96_MAX - _depositedAssets; uint256 _yieldVaultMaxDeposit = _yieldVault.maxDeposit(address(this)); // Vault shares are minted 1:1 when the vault is collateralized, // so maxDeposit and maxMint return the same value return _yieldVaultMaxDeposit < _vaultMaxDeposit ? _yieldVaultMaxDeposit : _vaultMaxDeposit; } /** * @notice Returns the maximum amount of the underlying asset that can be withdrawn * from the owner balance in the Vault, through a withdraw call. * @param _owner Address to check `maxWithdraw` for * @return uint256 Amount of the underlying asset that can be withdrawn */ function _maxWithdraw(address _owner) internal view returns (uint256) { return _convertToAssets(_balanceOf(_owner), _totalSupply(), _totalAssets(), Math.Rounding.Down); } /** * @notice Returns the maximum amount of Vault shares that can be redeemed * from the owner balance in the Vault, through a redeem call. * @param _owner Address to check `maxRedeem` for * @return uint256 Amount of Vault shares that can be redeemed */ function _maxRedeem(address _owner) internal view returns (uint256) { return _balanceOf(_owner); } /* ============ Yield Functions ============ */ /** * @notice Total available yield amount accrued by this vault. * @dev This amount includes the liquidatable yield + yield fee amount. * @dev The available yield is equal to the total amount of assets managed by this Vault * minus the total amount of assets supplied to the Vault and current allocated `_yieldFeeShares`. * @dev If `_assetsAllocated` is greater than `_withdrawableAssets`, it means that the Vault is undercollateralized. * We must not mint more shares than underlying assets available so we return 0. * @return uint256 Total yield amount */ function _availableYieldBalance() internal view returns (uint256) { uint256 _depositedAssets = _totalSupply(); uint256 _withdrawableAssets = _totalAssets(); uint256 _assetsAllocated = _convertToAssets( _depositedAssets + _yieldFeeShares, _depositedAssets, _withdrawableAssets, Math.Rounding.Up ); return _assetsAllocated > _withdrawableAssets ? 0 : _withdrawableAssets - _assetsAllocated; } /** * @notice Available yield fee amount. * @param _availableYield Total amount of yield available * @return uint256 Available yield fee balance */ function _availableYieldFeeBalance(uint256 _availableYield) internal view returns (uint256) { return (_availableYield * _yieldFeePercentage) / FEE_PRECISION; } /** * @notice Increase yield fee balance accrued by `_yieldFeeRecipient`. * @param _shares Amount of shares to increase yield fee balance by */ function _increaseYieldFeeBalance(uint256 _shares) internal { _yieldFeeShares += _shares; } /* ============ Liquidation Functions ============ */ /** * @notice Return the yield amount (available yield minus fees) that can be liquidated by minting Vault shares. * @param _token Address of the token to get available balance for * @return uint256 Available amount of `_token` */ function _liquidatableBalanceOf(address _token) internal view returns (uint256) { if (_token != address(this)) revert LiquidationTokenOutNotVaultShare(_token, address(this)); uint256 _availableYield = _availableYieldBalance(); unchecked { return _availableYield -= _availableYieldFeeBalance(_availableYield); } } /* ============ Deposit Functions ============ */ /** * @notice Deposit assets and mint shares * @param _caller The caller of the deposit * @param _receiver The receiver of the deposit shares * @param _assets Amount of assets to deposit * @dev If there are currently some underlying assets in the vault, * we only transfer the difference from the user wallet into the vault. * The difference is calculated this way: * - if `_vaultAssets` balance is greater than 0 and lower than `_assets`, * we subtract `_vaultAssets` from `_assets` and deposit `_assetsDeposit` amount into the vault * - if `_vaultAssets` balance is greater than or equal to `_assets`, * we know the vault has enough underlying assets to fulfill the deposit * so we don't transfer any assets from the user wallet into the vault * @dev Will revert if 0 shares are minted back to the receiver. */ function _deposit(address _caller, address _receiver, uint256 _assets) internal { // It is only possible to deposit when the vault is collateralized // Shares are backed 1:1 by assets if (_assets == 0) revert MintZeroShares(); uint256 _vaultAssets = _asset.balanceOf(address(this)); // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the // `tokensToSend` hook. On the other hand, the `tokenReceived` hook that is triggered after the transfer // calls the vault which is assumed to not be malicious. // // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the // assets are transferred and before the shares are minted, which is a valid state. // We only need to deposit new assets if there is not enough assets in the vault to fulfill the deposit if (_assets > _vaultAssets) { uint256 _assetsDeposit; unchecked { if (_vaultAssets != 0) { _assetsDeposit = _assets - _vaultAssets; } } _asset.safeTransferFrom( _caller, address(this), _assetsDeposit != 0 ? _assetsDeposit : _assets ); } _yieldVault.deposit(_assets, address(this)); _mint(_receiver, _assets); emit Deposit(_caller, _receiver, _assets, _assets); } /** * @notice Deposit assets and mint shares. * @dev Will revert if the Vault is under-collateralized. * So assets does not need to be converted to shares. * @param _assets The assets to deposit * @param _owner The owner of the assets * @param _receiver The receiver of the deposit shares * @param _isMint Whether the function is called to mint or deposit * @return uint256 Amount of shares minted to `_receiver` */ function _depositAssets( uint256 _assets, address _owner, address _receiver, bool _isMint ) internal returns (uint256) { uint256 _depositedAssets = _totalSupply(); uint256 _withdrawableAssets = _totalAssets(); _onlyVaultCollateralized(_depositedAssets, _withdrawableAssets); if (_assets > _maxDeposit(_depositedAssets)) { if (_isMint) { revert MintMoreThanMax(_receiver, _assets, _maxDeposit(_depositedAssets)); } revert DepositMoreThanMax(_receiver, _assets, _maxDeposit(_depositedAssets)); } _deposit(_owner, _receiver, _assets); return _assets; } /* ============ Redeem Function ============ */ /** * @notice Redeem/Withdraw common flow * @dev When the Vault is collateralized, shares are backed by assets 1:1, `withdraw` is used. * When the Vault is undercollateralized, shares are not backed by assets 1:1. * `redeem` is used to avoid burning too many YieldVault shares in exchange of assets. * @param _caller Address of the caller * @param _receiver Address of the receiver of the assets * @param _owner Owner of the shares * @param _shares Shares to burn * @param _assets Assets to withdraw * @param _vaultCollateralized Whether the Vault is collateralized or not */ function _redeem( address _caller, address _receiver, address _owner, uint256 _shares, uint256 _assets, bool _vaultCollateralized ) internal returns (uint256) { if (_caller != _owner) { _spendAllowance(_owner, _caller, _shares); } uint256 _yieldVaultShares; if (!_vaultCollateralized) { _yieldVaultShares = _shares.mulDiv( _yieldVault.maxRedeem(address(this)), _totalSupply(), Math.Rounding.Down ); } // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer, // calls the vault, which is assumed not malicious. // // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the // shares are burned and after the assets are transferred, which is a valid state. _burn(_owner, _shares); // If the Vault is collateralized, users can withdraw their deposit 1:1 if (_vaultCollateralized) { _yieldVault.withdraw(_assets, _receiver, address(this)); } else { // Otherwise, redeem is used to avoid burning too many YieldVault shares _assets = _yieldVault.redeem(_yieldVaultShares, _receiver, address(this)); } if (_assets == 0) revert WithdrawZeroAssets(); emit Withdraw(_caller, _receiver, _owner, _assets, _shares); return _assets; } /* ============ State Functions ============ */ /** * @notice Creates `_shares` tokens and assigns them to `_receiver`, increasing the total supply. * @dev Emits a {Transfer} event with `from` set to the zero address. * @dev `_receiver` cannot be the zero address. * @param _receiver Address that will receive the minted shares * @param _shares Shares to mint */ function _mint(address _receiver, uint256 _shares) internal virtual override { _twabController.mint(_receiver, SafeCast.toUint96(_shares)); emit Transfer(address(0), _receiver, _shares); } /** * @notice Destroys `_shares` tokens from `_owner`, reducing the total supply. * @dev Emits a {Transfer} event with `to` set to the zero address. * @dev `_owner` cannot be the zero address. * @dev `_owner` must have at least `_shares` tokens. * @param _owner The owner of the shares * @param _shares The shares to burn */ function _burn(address _owner, uint256 _shares) internal virtual override { _twabController.burn(_owner, SafeCast.toUint96(_shares)); emit Transfer(_owner, address(0), _shares); } /** * @notice Updates `_from` and `_to` TWAB balance for a transfer. * @dev `_from` cannot be the zero address. * @dev `_to` cannot be the zero address. * @dev `_from` must have a balance of at least `_shares`. * @param _from Address to transfer from * @param _to Address to transfer to * @param _shares Shares to transfer */ function _transfer(address _from, address _to, uint256 _shares) internal virtual override { _twabController.transfer(_from, _to, SafeCast.toUint96(_shares)); emit Transfer(_from, _to, _shares); } /** * @notice Returns the quantity of withdrawable underlying assets held as collateral by the YieldVault. * @dev When the Vault is collateralized, Vault shares are minted at a 1:1 ratio based on the user's deposited underlying assets. * The total supply of shares corresponds directly to the total amount of underlying assets deposited into the YieldVault. * Users have the ability to withdraw only the quantity of underlying assets they initially deposited, * without access to any of the accumulated yield within the YieldVault. * @dev In case of undercollateralization, any remaining collateral within the YieldVault can be withdrawn. * Withdrawals can be made by users for their corresponding deposit shares. * @param _depositedAssets Assets deposited into the YieldVault * @param _withdrawableAssets Assets withdrawable from the YieldVault * @return uint256 Available collateral */ function _collateral( uint256 _depositedAssets, uint256 _withdrawableAssets ) internal pure returns (uint256) { // If the Vault is collateralized, users can only withdraw the amount of underlying assets they deposited. if (_isVaultCollateralized(_depositedAssets, _withdrawableAssets)) { return _depositedAssets; } // Otherwise, any remaining collateral within the YieldVault is available // and distributed proportionally among depositors. return _withdrawableAssets; } /** * @notice Check if the Vault is collateralized. * @dev The vault is collateralized if the total amount of underlying assets currently held by the YieldVault * is greater than or equal to the total supply of shares minted by the Vault. * @param _depositedAssets Assets deposited into the YieldVault * @param _withdrawableAssets Assets withdrawable from the YieldVault * @return bool True if the vault is collateralized, false otherwise */ function _isVaultCollateralized( uint256 _depositedAssets, uint256 _withdrawableAssets ) internal pure returns (bool) { return _withdrawableAssets >= _depositedAssets; } /* ============ Setter Functions ============ */ /** * @notice Set claimer address. * @dev Will revert if `claimer_` is address zero. * @param claimer_ Address of the claimer */ function _setClaimer(address claimer_) internal { if (claimer_ == address(0)) revert ClaimerZeroAddress(); _claimer = claimer_; } /** * @notice Set yield fee percentage. * @dev Yield fee is represented in 9 decimals and can't exceed or equal `1e9`. * @param yieldFeePercentage_ The new yield fee percentage to set */ function _setYieldFeePercentage(uint32 yieldFeePercentage_) internal { if (yieldFeePercentage_ >= FEE_PRECISION) { revert YieldFeePercentageGtePrecision(yieldFeePercentage_, FEE_PRECISION); } _yieldFeePercentage = yieldFeePercentage_; } /** * @notice Set yield fee recipient address. * @param yieldFeeRecipient_ Address of the fee recipient */ function _setYieldFeeRecipient(address yieldFeeRecipient_) internal { _yieldFeeRecipient = yieldFeeRecipient_; } }
// 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) (interfaces/IERC4626.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; import "../token/ERC20/extensions/IERC20Metadata.sol"; /** * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626]. * * _Available since v4.7._ */ interface IERC4626 is IERC20, IERC20Metadata { event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares); event Withdraw( address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); /** * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing. * * - MUST be an ERC-20 token contract. * - MUST NOT revert. */ function asset() external view returns (address assetTokenAddress); /** * @dev Returns the total amount of the underlying asset that is “managed” by Vault. * * - SHOULD include any compounding that occurs from yield. * - MUST be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT revert. */ function totalAssets() external view returns (uint256 totalManagedAssets); /** * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal * scenario where all the conditions are met. * * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT show any variations depending on the caller. * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. * - MUST NOT revert. * * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and * from. */ function convertToShares(uint256 assets) external view returns (uint256 shares); /** * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal * scenario where all the conditions are met. * * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT show any variations depending on the caller. * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. * - MUST NOT revert. * * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and * from. */ function convertToAssets(uint256 shares) external view returns (uint256 assets); /** * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver, * through a deposit call. * * - MUST return a limited value if receiver is subject to some deposit limit. * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited. * - MUST NOT revert. */ function maxDeposit(address receiver) external view returns (uint256 maxAssets); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given * current on-chain conditions. * * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called * in the same transaction. * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the * deposit would be accepted, regardless if the user has enough tokens approved, etc. * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by depositing. */ function previewDeposit(uint256 assets) external view returns (uint256 shares); /** * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens. * * - MUST emit the Deposit event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * deposit execution, and are accounted for during deposit. * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not * approving enough underlying tokens to the Vault contract, etc). * * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. */ function deposit(uint256 assets, address receiver) external returns (uint256 shares); /** * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call. * - MUST return a limited value if receiver is subject to some mint limit. * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted. * - MUST NOT revert. */ function maxMint(address receiver) external view returns (uint256 maxShares); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given * current on-chain conditions. * * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the * same transaction. * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint * would be accepted, regardless if the user has enough tokens approved, etc. * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by minting. */ function previewMint(uint256 shares) external view returns (uint256 assets); /** * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens. * * - MUST emit the Deposit event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint * execution, and are accounted for during mint. * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not * approving enough underlying tokens to the Vault contract, etc). * * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. */ function mint(uint256 shares, address receiver) external returns (uint256 assets); /** * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the * Vault, through a withdraw call. * * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. * - MUST NOT revert. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, * given current on-chain conditions. * * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if * called * in the same transaction. * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though * the withdrawal would be accepted, regardless if the user has enough shares, etc. * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by depositing. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares); /** * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver. * * - MUST emit the Withdraw event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * withdraw execution, and are accounted for during withdraw. * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner * not having enough shares, etc). * * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. * Those methods should be performed separately. */ function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares); /** * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, * through a redeem call. * * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. * - MUST NOT revert. */ function maxRedeem(address owner) external view returns (uint256 maxShares); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, * given current on-chain conditions. * * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the * same transaction. * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the * redemption would be accepted, regardless if the user has enough shares, etc. * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by redeeming. */ function previewRedeem(uint256 shares) external view returns (uint256 assets); /** * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver. * * - MUST emit the Withdraw event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * redeem execution, and are accounted for during redeem. * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner * not having enough shares, etc). * * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed. * Those methods should be performed separately. */ function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.4) (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") {} /** * @inheritdoc IERC20Permit */ 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); } /** * @inheritdoc IERC20Permit */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @inheritdoc IERC20Permit */ // 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.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.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.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 pragma solidity ^0.8.0; /** * @title Abstract ownable contract that can be inherited by other contracts * @notice Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The `owner` is first set by passing the address of the `initialOwner` to the Ownable constructor. * * The owner account can be transferred through a two steps process: * 1. The current `owner` calls {transferOwnership} to set a `pendingOwner` * 2. The `pendingOwner` calls {claimOwnership} to accept the ownership transfer * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to the owner. */ abstract contract Ownable { address private _owner; address private _pendingOwner; /** * @dev Emitted when `_pendingOwner` has been changed. * @param pendingOwner new `_pendingOwner` address. */ event OwnershipOffered(address indexed pendingOwner); /** * @dev Emitted when `_owner` has been changed. * @param previousOwner previous `_owner` address. * @param newOwner new `_owner` address. */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /* ============ Deploy ============ */ /** * @notice Initializes the contract setting `_initialOwner` as the initial owner. * @param _initialOwner Initial owner of the contract. */ constructor(address _initialOwner) { _setOwner(_initialOwner); } /* ============ External Functions ============ */ /** * @notice Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @notice Gets current `_pendingOwner`. * @return Current `_pendingOwner` address. */ function pendingOwner() external view virtual returns (address) { return _pendingOwner; } /** * @notice Renounce ownership of the contract. * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() external virtual onlyOwner { _setOwner(address(0)); } /** * @notice Allows current owner to set the `_pendingOwner` address. * @param _newOwner Address to transfer ownership to. */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Ownable/pendingOwner-not-zero-address"); _pendingOwner = _newOwner; emit OwnershipOffered(_newOwner); } /** * @notice Allows the `_pendingOwner` address to finalize the transfer. * @dev This function is only callable by the `_pendingOwner`. */ function claimOwnership() external onlyPendingOwner { _setOwner(_pendingOwner); _pendingOwner = address(0); } /* ============ Internal Functions ============ */ /** * @notice Internal function to set the `_owner` of the contract. * @param _newOwner New `_owner` address. */ function _setOwner(address _newOwner) private { address _oldOwner = _owner; _owner = _newOwner; emit OwnershipTransferred(_oldOwner, _newOwner); } /* ============ Modifier Functions ============ */ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable/caller-not-owner"); _; } /** * @dev Throws if called by any account other than the `pendingOwner`. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable/caller-not-pendingOwner"); _; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ILiquidationSource { /** * @notice Emitted when a new liquidation pair is set for the given `tokenOut`. * @param tokenOut The token being liquidated * @param liquidationPair The new liquidation pair for the token */ event LiquidationPairSet(address indexed tokenOut, address indexed liquidationPair); /** * @notice Get the available amount of tokens that can be swapped. * @param tokenOut Address of the token to get available balance for * @return uint256 Available amount of `token` */ function liquidatableBalanceOf(address tokenOut) external returns (uint256); /** * @notice Transfers tokens to the receiver * @param sender Address that triggered the liquidation * @param receiver Address of the account that will receive `tokenOut` * @param tokenOut Address of the token being bought * @param amountOut Amount of token being bought */ function transferTokensOut( address sender, address receiver, address tokenOut, uint256 amountOut ) external returns (bytes memory); /** * @notice Verifies that tokens have been transferred in. * @param tokenIn Address of the token being sold * @param amountIn Amount of token being sold * @param transferTokensOutData Data returned by the corresponding transferTokensOut call */ function verifyTokensIn( address tokenIn, uint256 amountIn, bytes calldata transferTokensOutData ) external; /** * @notice Get the address that will receive `tokenIn`. * @param tokenIn Address of the token to get the target address for * @return address Address of the target */ function targetOf(address tokenIn) external returns (address); /** * @notice Checks if a liquidation pair can be used to liquidate the given tokenOut from this source. * @param tokenOut The address of the token to liquidate * @param liquidationPair The address of the liquidation pair that is being checked * @return bool True if the liquidation pair can be used, false otherwise */ function isLiquidationPair(address tokenOut, address liquidationPair) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { SafeCast } from "openzeppelin/utils/math/SafeCast.sol"; import { Ownable } from "openzeppelin/access/Ownable.sol"; import { IERC20 } from "openzeppelin/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin/token/ERC20/utils/SafeERC20.sol"; import { SD59x18, sd } from "prb-math/SD59x18.sol"; import { SD1x18, unwrap, UNIT } from "prb-math/SD1x18.sol"; import { TwabController } from "pt-v5-twab-controller/TwabController.sol"; import { UD34x4, intoUD60x18 as fromUD34x4toUD60x18 } from "./libraries/UD34x4.sol"; import { DrawAccumulatorLib, Observation } from "./libraries/DrawAccumulatorLib.sol"; import { TieredLiquidityDistributor, Tier } from "./abstract/TieredLiquidityDistributor.sol"; import { TierCalculationLib } from "./libraries/TierCalculationLib.sol"; /// @notice Emitted when the prize pool is constructed with a first draw open timestamp that is in the past error FirstDrawOpensInPast(); /// @notice Emitted when the Twab Controller has an incompatible period length error IncompatibleTwabPeriodLength(); /// @notice Emitted when the Twab Controller has an incompatible period offset error IncompatibleTwabPeriodOffset(); /// @notice Emitted when someone tries to set the draw manager with the zero address error DrawManagerIsZeroAddress(); /// @notice Emitted when the caller is not the deployer. error NotDeployer(); /// @notice Emitted when someone tries to withdraw too many rewards. /// @param requested The requested reward amount to withdraw /// @param available The total reward amount available for the caller to withdraw error InsufficientRewardsError(uint256 requested, uint256 available); /// @notice Emitted when an address did not win the specified prize on a vault when claiming. /// @param winner The address checked for the prize /// @param vault The vault address /// @param tier The prize tier /// @param prizeIndex The prize index error DidNotWin(address vault, address winner, uint8 tier, uint32 prizeIndex); /// @notice Emitted when the fee being claimed is larger than the max allowed fee. /// @param fee The fee being claimed /// @param maxFee The max fee that can be claimed error FeeTooLarge(uint256 fee, uint256 maxFee); /// @notice Emitted when the initialized smoothing number is not less than one. /// @param smoothing The unwrapped smoothing value that exceeds the limit error SmoothingGTEOne(int64 smoothing); /// @notice Emitted when the contributed amount is more than the available, un-accounted balance. /// @param amount The contribution amount that is being claimed /// @param available The available un-accounted balance that can be claimed as a contribution error ContributionGTDeltaBalance(uint256 amount, uint256 available); /// @notice Emitted when the withdraw amount is greater than the available reserve. /// @param amount The amount being withdrawn /// @param reserve The total reserve available for withdrawal error InsufficientReserve(uint104 amount, uint104 reserve); /// @notice Emitted when the winning random number is zero. error RandomNumberIsZero(); /// @notice Emitted when the draw cannot be awarded since it has not closed. /// @param drawClosesAt The timestamp in seconds at which the draw closes error AwardingDrawNotClosed(uint48 drawClosesAt); /// @notice Emitted when prize index is greater or equal to the max prize count for the tier. /// @param invalidPrizeIndex The invalid prize index /// @param prizeCount The prize count for the tier /// @param tier The tier number error InvalidPrizeIndex(uint32 invalidPrizeIndex, uint32 prizeCount, uint8 tier); /// @notice Emitted when there are no awarded draws when a computation requires an awarded draw. error NoDrawsAwarded(); /// @notice Emitted when attempting to claim from a tier that does not exist. /// @param tier The tier number that does not exist /// @param numberOfTiers The current number of tiers error InvalidTier(uint8 tier, uint8 numberOfTiers); /// @notice Emitted when the caller is not the draw manager. /// @param caller The caller address /// @param drawManager The drawManager address error CallerNotDrawManager(address caller, address drawManager); /// @notice Emitted when someone tries to claim a prize that is zero size error PrizeIsZero(); /// @notice Emitted when someone tries to claim a prize, but sets the fee recipient address to the zero address. error FeeRecipientZeroAddress(); /// @notice Emitted when a claim is attempted after the claiming period has expired. error ClaimPeriodExpired(); /** * @notice Constructor Parameters * @param prizeToken The token to use for prizes * @param twabController The Twab Controller to retrieve time-weighted average balances from * @param drawPeriodSeconds The number of seconds between draws. E.g. a Prize Pool with a daily draw should have a draw period of 86400 seconds. * @param firstDrawOpensAt The timestamp at which the first draw will open. * @param numberOfTiers The number of tiers to start with. Must be greater than or equal to the minimum number of tiers. * @param tierShares The number of shares to allocate to each tier * @param reserveShares The number of shares to allocate to the reserve. * @param smoothing The amount of smoothing to apply to vault contributions. Must be less than 1. A value of 0 is no smoothing, while greater values smooth until approaching infinity */ struct ConstructorParams { IERC20 prizeToken; TwabController twabController; uint48 drawPeriodSeconds; uint48 firstDrawOpensAt; SD1x18 smoothing; uint24 grandPrizePeriodDraws; uint8 numberOfTiers; uint8 tierShares; uint8 reserveShares; } /** * @title PoolTogether V5 Prize Pool * @author PoolTogether Inc Team * @notice The Prize Pool holds the prize liquidity and allows vaults to claim prizes. */ contract PrizePool is TieredLiquidityDistributor, Ownable { using SafeERC20 for IERC20; /* ============ Events ============ */ /// @notice Emitted when a prize is claimed. /// @param vault The address of the vault that claimed the prize. /// @param winner The address of the winner /// @param recipient The address of the prize recipient /// @param drawId The draw ID of the draw that was claimed. /// @param tier The prize tier that was claimed. /// @param payout The amount of prize tokens that were paid out to the winner /// @param fee The amount of prize tokens that were paid to the claimer /// @param feeRecipient The address that the claim fee was sent to event ClaimedPrize( address indexed vault, address indexed winner, address indexed recipient, uint24 drawId, uint8 tier, uint32 prizeIndex, uint152 payout, uint96 fee, address feeRecipient ); /// @notice Emitted when a draw is awarded. /// @param drawId The ID of the draw that was awarded /// @param winningRandomNumber The winning random number for the awarded draw /// @param lastNumTiers The previous number of prize tiers /// @param numTiers The number of prize tiers for the awarded draw /// @param reserve The resulting reserve available /// @param prizeTokensPerShare The amount of prize tokens per share for the awarded draw /// @param drawOpenedAt The start timestamp of the awarded draw event DrawAwarded( uint24 indexed drawId, uint256 winningRandomNumber, uint8 lastNumTiers, uint8 numTiers, uint104 reserve, UD34x4 prizeTokensPerShare, uint48 drawOpenedAt ); /// @notice Emitted when any amount of the reserve is rewarded to a recipient. /// @param to The recipient of the reward /// @param amount The amount of assets rewarded event AllocateRewardFromReserve(address indexed to, uint256 amount); /// @notice Emitted when the reserve is manually increased. /// @param user The user who increased the reserve /// @param amount The amount of assets transferred event ContributedReserve(address indexed user, uint256 amount); /// @notice Emitted when a vault contributes prize tokens to the pool. /// @param vault The address of the vault that is contributing tokens /// @param drawId The ID of the first draw that the tokens will be contributed to /// @param amount The amount of tokens contributed event ContributePrizeTokens(address indexed vault, uint24 indexed drawId, uint256 amount); /// @notice Emitted when an address withdraws their prize claim rewards. /// @param account The account that is withdrawing rewards /// @param to The address the rewards are sent to /// @param amount The amount withdrawn /// @param available The total amount that was available to withdraw before the transfer event WithdrawRewards( address indexed account, address indexed to, uint256 amount, uint256 available ); /// @notice Emitted when an address receives new prize claim rewards. /// @param to The address the rewards are given to /// @param amount The amount increased event IncreaseClaimRewards(address indexed to, uint256 amount); /// @notice Emitted when the drawManager is set. /// @param drawManager The draw manager event DrawManagerSet(address indexed drawManager); /* ============ State ============ */ /// @notice The DrawAccumulator that tracks the exponential moving average of the contributions by a vault. mapping(address vault => DrawAccumulatorLib.Accumulator accumulator) internal _vaultAccumulator; /// @notice Records the claim record for a winner. mapping(address vault => mapping(address account => mapping(uint24 drawId => mapping(uint8 tier => mapping(uint32 prizeIndex => bool claimed))))) internal _claimedPrizes; /// @notice Tracks the total rewards accrued for a claimer or draw completer. mapping(address recipient => uint256 rewards) internal _rewards; /// @notice The degree of POOL contribution smoothing. 0 = no smoothing, ~1 = max smoothing. /// @dev Smoothing spreads out vault contribution over multiple draws; the higher the smoothing the more draws. SD1x18 public immutable smoothing; /// @notice The token that is being contributed and awarded as prizes. IERC20 public immutable prizeToken; /// @notice The Twab Controller to use to retrieve historic balances. TwabController public immutable twabController; /// @notice The draw manager address. address public drawManager; /// @notice The number of seconds between draws. uint48 public immutable drawPeriodSeconds; /// @notice The timestamp at which the first draw will open. uint48 public immutable firstDrawOpensAt; /// @notice The exponential weighted average of all vault contributions. DrawAccumulatorLib.Accumulator internal _totalAccumulator; /// @notice The winner random number for the last awarded draw. uint256 internal _winningRandomNumber; /// @notice The number of prize claims for the last awarded draw. uint32 public claimCount; /// @notice The total amount of prize tokens that have been claimed for all time. uint128 internal _totalWithdrawn; /// @notice Tracks reserve that was contributed directly to the reserve. Always increases. uint96 internal _directlyContributedReserve; /* ============ Constructor ============ */ /// @notice Constructs a new Prize Pool. /// @param params A struct of constructor parameters constructor( ConstructorParams memory params ) TieredLiquidityDistributor( params.numberOfTiers, params.tierShares, params.reserveShares, params.grandPrizePeriodDraws ) Ownable() { if (unwrap(params.smoothing) >= unwrap(UNIT)) { revert SmoothingGTEOne(unwrap(params.smoothing)); } if (params.firstDrawOpensAt < block.timestamp) { revert FirstDrawOpensInPast(); } uint48 twabPeriodOffset = params.twabController.PERIOD_OFFSET(); uint48 twabPeriodLength = params.twabController.PERIOD_LENGTH(); if ( params.drawPeriodSeconds < twabPeriodLength || params.drawPeriodSeconds % twabPeriodLength != 0 ) { revert IncompatibleTwabPeriodLength(); } if ((params.firstDrawOpensAt - twabPeriodOffset) % twabPeriodLength != 0) { revert IncompatibleTwabPeriodOffset(); } prizeToken = params.prizeToken; twabController = params.twabController; smoothing = params.smoothing; drawPeriodSeconds = params.drawPeriodSeconds; firstDrawOpensAt = params.firstDrawOpensAt; } /* ============ Modifiers ============ */ /// @notice Modifier that throws if sender is not the draw manager. modifier onlyDrawManager() { if (msg.sender != drawManager) { revert CallerNotDrawManager(msg.sender, drawManager); } _; } /* ============ External Write Functions ============ */ /// @notice Allows a caller to set the DrawManager if not already set. /// @param _drawManager The draw manager function setDrawManager(address _drawManager) external onlyOwner { if (_drawManager == address(0)) { revert DrawManagerIsZeroAddress(); } drawManager = _drawManager; emit DrawManagerSet(_drawManager); } /// @notice Contributes prize tokens on behalf of the given vault. /// @dev The tokens should have already been transferred to the prize pool. /// @dev The prize pool balance will be checked to ensure there is at least the given amount to deposit. /// @param _prizeVault The address of the vault to contribute to /// @param _amount The amount of prize tokens to contribute /// @return The amount of available prize tokens prior to the contribution. function contributePrizeTokens(address _prizeVault, uint256 _amount) external returns (uint256) { uint256 _deltaBalance = prizeToken.balanceOf(address(this)) - _accountedBalance(); if (_deltaBalance < _amount) { revert ContributionGTDeltaBalance(_amount, _deltaBalance); } uint24 openDrawId_ = _openDrawId(); SD59x18 _smoothing = smoothing.intoSD59x18(); DrawAccumulatorLib.add(_vaultAccumulator[_prizeVault], _amount, openDrawId_, _smoothing); DrawAccumulatorLib.add(_totalAccumulator, _amount, openDrawId_, _smoothing); emit ContributePrizeTokens(_prizeVault, openDrawId_, _amount); return _deltaBalance; } /// @notice Allows the Manager to allocate a reward from the reserve to a recipient. /// @param _to The address to allocate the rewards to /// @param _amount The amount of tokens for the reward function allocateRewardFromReserve(address _to, uint96 _amount) external onlyDrawManager { if (_amount > _reserve) { revert InsufficientReserve(_amount, _reserve); } unchecked { _reserve -= _amount; } _rewards[_to] += _amount; emit AllocateRewardFromReserve(_to, _amount); } /// @notice Allows the Manager to award a draw with the winning random number. /// @dev Updates the number of tiers, the winning random number and the prize pool reserve. /// @param winningRandomNumber_ The winning random number for the draw /// @return The ID of the awarded draw function awardDraw(uint256 winningRandomNumber_) external onlyDrawManager returns (uint24) { // check winning random number if (winningRandomNumber_ == 0) { revert RandomNumberIsZero(); } uint24 awardingDrawId = _drawIdToAward(); uint48 awardingDrawOpenedAt = _drawOpensAt(awardingDrawId); uint48 awardingDrawClosedAt = awardingDrawOpenedAt + drawPeriodSeconds; if (block.timestamp < awardingDrawClosedAt) { revert AwardingDrawNotClosed(awardingDrawClosedAt); } uint24 lastAwardedDrawId_ = _lastAwardedDrawId; uint32 _claimCount = claimCount; uint8 _numTiers = numberOfTiers; uint8 _nextNumberOfTiers = _numTiers; if (lastAwardedDrawId_ != 0) { _nextNumberOfTiers = _computeNextNumberOfTiers(_claimCount); } /** @dev If any draws were skipped from the last awarded draw to the one we are awarding, the contribution from those skipped draws will be included in the new distributions. */ _awardDraw( awardingDrawId, _nextNumberOfTiers, _getTotalContributedBetween(lastAwardedDrawId_ + 1, awardingDrawId) ); _winningRandomNumber = winningRandomNumber_; if (_claimCount != 0) { claimCount = 0; } emit DrawAwarded( awardingDrawId, winningRandomNumber_, _numTiers, _nextNumberOfTiers, _reserve, prizeTokenPerShare, awardingDrawOpenedAt ); return awardingDrawId; } /** * @notice Claims a prize for a given winner and tier. * @dev This function takes in an address _winner, a uint8 _tier, a uint96 _fee, and an * address _feeRecipient. It checks if _winner is actually the winner of the _tier for the calling vault. * If so, it calculates the prize size and transfers it to the winner. If not, it reverts with an error message. * The function then checks the claim record of _winner to see if they have already claimed the prize for the * awarded draw. If not, it updates the claim record with the claimed tier and emits a ClaimedPrize event with * information about the claim. * Note that this function can modify the state of the contract by updating the claim record, changing the largest * tier claimed and the claim count, and transferring prize tokens. The function is marked as external which * means that it can be called from outside the contract. * @param _tier The tier of the prize to be claimed. * @param _winner The address of the eligible winner * @param _prizeIndex The prize to claim for the winner. Must be less than the prize count for the tier. * @param _prizeRecipient The recipient of the prize * @param _fee The fee associated with claiming the prize. * @param _feeRecipient The address to receive the fee. * @return Total prize amount claimed (payout and fees combined). If the prize was already claimed it returns zero. */ function claimPrize( address _winner, uint8 _tier, uint32 _prizeIndex, address _prizeRecipient, uint96 _fee, address _feeRecipient ) external returns (uint256) { /** * @dev Claims cannot occur after a draw has been finalized (1 period after a draw closes). This prevents * the reserve from changing while the following draw is being awarded. */ uint24 lastAwardedDrawId_ = _lastAwardedDrawId; if (_isDrawFinalized(lastAwardedDrawId_)) { revert ClaimPeriodExpired(); } if (_feeRecipient == address(0) && _fee > 0) { revert FeeRecipientZeroAddress(); } uint8 _numTiers = numberOfTiers; Tier memory tierLiquidity = _getTier(_tier, _numTiers); if (_fee > tierLiquidity.prizeSize) { revert FeeTooLarge(_fee, tierLiquidity.prizeSize); } if (tierLiquidity.prizeSize == 0) { revert PrizeIsZero(); } { // hide the variables! ( SD59x18 _vaultPortion, SD59x18 _computedTierOdds, uint24 _drawDuration ) = _computeVaultTierDetails(msg.sender, _tier, _numTiers, lastAwardedDrawId_); if ( !_isWinner( lastAwardedDrawId_, msg.sender, _winner, _tier, _prizeIndex, _vaultPortion, _computedTierOdds, _drawDuration ) ) { revert DidNotWin(msg.sender, _winner, _tier, _prizeIndex); } } if (_claimedPrizes[msg.sender][_winner][lastAwardedDrawId_][_tier][_prizeIndex]) { return 0; } _claimedPrizes[msg.sender][_winner][lastAwardedDrawId_][_tier][_prizeIndex] = true; // `amount` is a snapshot of the reserve before consuming liquidity _consumeLiquidity(tierLiquidity, _tier, tierLiquidity.prizeSize); // `amount` is now the payout amount uint256 amount; if (_fee != 0) { emit IncreaseClaimRewards(_feeRecipient, _fee); _rewards[_feeRecipient] += _fee; unchecked { amount = tierLiquidity.prizeSize - _fee; } } else { amount = tierLiquidity.prizeSize; } // co-locate to save gas claimCount++; _totalWithdrawn = SafeCast.toUint128(_totalWithdrawn + amount); emit ClaimedPrize( msg.sender, _winner, _prizeRecipient, lastAwardedDrawId_, _tier, _prizeIndex, uint152(amount), _fee, _feeRecipient ); prizeToken.safeTransfer(_prizeRecipient, amount); return tierLiquidity.prizeSize; } /** * @notice Withdraws earned rewards for the caller. * @param _to The address to transfer the rewards to * @param _amount The amount of rewards to withdraw */ function withdrawRewards(address _to, uint256 _amount) external { uint256 _available = _rewards[msg.sender]; if (_amount > _available) { revert InsufficientRewardsError(_amount, _available); } unchecked { _rewards[msg.sender] = _available - _amount; } _transfer(_to, _amount); emit WithdrawRewards(msg.sender, _to, _amount, _available); } /// @notice Allows anyone to deposit directly into the Prize Pool reserve. /// @dev Ensure caller has sufficient balance and has approved the Prize Pool to transfer the tokens /// @param _amount The amount of tokens to increase the reserve by function contributeReserve(uint96 _amount) external { _reserve += _amount; _directlyContributedReserve += _amount; prizeToken.safeTransferFrom(msg.sender, address(this), _amount); emit ContributedReserve(msg.sender, _amount); } /* ============ External Read Functions ============ */ /// @notice Returns the winning random number for the last awarded draw. /// @return The winning random number function getWinningRandomNumber() external view returns (uint256) { return _winningRandomNumber; } /// @notice Returns the last awarded draw id. /// @return The last awarded draw id function getLastAwardedDrawId() external view returns (uint24) { return _lastAwardedDrawId; } /// @notice Returns the total prize tokens contributed between the given draw ids, inclusive. /// @dev Note that this is after smoothing is applied. /// @param _startDrawIdInclusive Start draw id inclusive /// @param _endDrawIdInclusive End draw id inclusive /// @return The total prize tokens contributed by all vaults function getTotalContributedBetween( uint24 _startDrawIdInclusive, uint24 _endDrawIdInclusive ) external view returns (uint256) { return _getTotalContributedBetween(_startDrawIdInclusive, _endDrawIdInclusive); } /// @notice Returns the total prize tokens contributed by a particular vault between the given draw ids, inclusive. /// @dev Note that this is after smoothing is applied. /// @param _vault The address of the vault /// @param _startDrawIdInclusive Start draw id inclusive /// @param _endDrawIdInclusive End draw id inclusive /// @return The total prize tokens contributed by the given vault function getContributedBetween( address _vault, uint24 _startDrawIdInclusive, uint24 _endDrawIdInclusive ) external view returns (uint256) { return DrawAccumulatorLib.getDisbursedBetween( _vaultAccumulator[_vault], _startDrawIdInclusive, _endDrawIdInclusive, smoothing.intoSD59x18() ); } /// @notice Computes the expected duration prize accrual for a tier. /// @param _tier The tier to check /// @return The number of draws function getTierAccrualDurationInDraws(uint8 _tier) external view returns (uint24) { return uint24(TierCalculationLib.estimatePrizeFrequencyInDraws(_tierOdds(_tier, numberOfTiers))); } /// @notice The total amount of prize tokens that have been claimed for all time /// @return The total amount of prize tokens that have been claimed for all time function totalWithdrawn() external view returns (uint256) { return _totalWithdrawn; } /// @notice Computes how many tokens have been accounted for /// @return The balance of tokens that have been accounted for function accountedBalance() external view returns (uint256) { return _accountedBalance(); } /// @notice Returns the open draw ID. /// @dev The open draw is the draw to which contributions can currently be made. /// @return The open draw ID function getOpenDrawId() external view returns (uint24) { return _openDrawId(); } /// @notice Returns the next draw ID that can be awarded. /// @dev It's possible for draws to be missed, so the next draw ID to award /// may be more than one draw ahead of the last awarded draw ID. /// @return The ID of the next draw that can be awarded function getDrawIdToAward() external view returns (uint24) { return _drawIdToAward(); } /// @notice Returns the time at which a draw opens / opened at. /// @param drawId The draw to get the timestamp for /// @return The start time of the draw in seconds function drawOpensAt(uint24 drawId) external view returns (uint48) { return _drawOpensAt(drawId); } /// @notice Returns the time at which a draw closes / closed at. /// @param drawId The draw to get the timestamp for /// @return The end time of the draw in seconds function drawClosesAt(uint24 drawId) external view returns (uint48) { return _drawClosesAt(drawId); } /// @notice Checks if the given draw is finalized. /// @param drawId The draw to check /// @return True if the draw is finalized, false otherwise function isDrawFinalized(uint24 drawId) external view returns (bool) { return _isDrawFinalized(drawId); } /// @notice Returns the amount of tokens that will be added to the reserve when next draw to award is awarded. /// @dev Intended for Draw manager to use after a draw has closed but not yet been awarded. /// @return The amount of prize tokens that will be added to the reserve function pendingReserveContributions() external view returns (uint256) { uint8 _numTiers = numberOfTiers; uint24 lastAwardedDrawId_ = _lastAwardedDrawId; (uint104 newReserve, ) = _computeNewDistributions( _numTiers, lastAwardedDrawId_ == 0 ? _numTiers : _computeNextNumberOfTiers(claimCount), fromUD34x4toUD60x18(prizeTokenPerShare), _getTotalContributedBetween(lastAwardedDrawId_ + 1, _drawIdToAward()) ); return newReserve; } /// @notice Returns whether the winner has claimed the tier for the last awarded draw /// @param _vault The vault to check /// @param _winner The account to check /// @param _tier The tier to check /// @param _prizeIndex The prize index to check /// @return True if the winner claimed the tier for the last awarded draw, false otherwise. function wasClaimed( address _vault, address _winner, uint8 _tier, uint32 _prizeIndex ) external view returns (bool) { return _claimedPrizes[_vault][_winner][_lastAwardedDrawId][_tier][_prizeIndex]; } /** * @notice Returns the balance of rewards earned for the given address. * @param _recipient The recipient to retrieve the reward balance for * @return The balance of rewards for the given recipient */ function rewardBalance(address _recipient) external view returns (uint256) { return _rewards[_recipient]; } /** * @notice Checks if the given user has won the prize for the specified tier in the given vault. * @param _vault The address of the vault to check. * @param _user The address of the user to check for the prize. * @param _tier The tier for which the prize is to be checked. * @param _prizeIndex The index of the prize to check (less than prize count for tier) * @return A boolean value indicating whether the user has won the prize or not. */ function isWinner( address _vault, address _user, uint8 _tier, uint32 _prizeIndex ) external view returns (bool) { uint24 lastAwardedDrawId_ = _lastAwardedDrawId; (SD59x18 vaultPortion, SD59x18 tierOdds, uint24 drawDuration) = _computeVaultTierDetails( _vault, _tier, numberOfTiers, lastAwardedDrawId_ ); return _isWinner( lastAwardedDrawId_, _vault, _user, _tier, _prizeIndex, vaultPortion, tierOdds, drawDuration ); } /** * @notice Returns the time-weighted average balance (TWAB) and the TWAB total supply for the specified user in the given vault over a specified period. * @param _vault The address of the vault for which to get the TWAB. * @param _user The address of the user for which to get the TWAB. * @param _drawDuration The duration of the period over which to calculate the TWAB, in number of draw periods. * @return The TWAB and the TWAB total supply for the specified user in the given vault over the specified period. */ function getVaultUserBalanceAndTotalSupplyTwab( address _vault, address _user, uint256 _drawDuration ) external view returns (uint256, uint256) { return _getVaultUserBalanceAndTotalSupplyTwab(_vault, _user, _drawDuration); } /** * @notice Returns the portion of a vault's contributions in a given draw range as a fraction. * @param _vault The address of the vault to calculate the contribution portion for. * @param _startDrawId The starting draw ID of the draw range to calculate the contribution portion for. * @param _endDrawId The ending draw ID of the draw range to calculate the contribution portion for. * @return The portion of the _vault's contributions in the given draw range as an SD59x18 value. */ function getVaultPortion( address _vault, uint24 _startDrawId, uint24 _endDrawId ) external view returns (SD59x18) { return _getVaultPortion(_vault, _startDrawId, _endDrawId); } /** * @notice Computes and returns the next number of tiers based on the current prize claim counts. This number may change throughout the draw * @return The next number of tiers */ function estimateNextNumberOfTiers() external view returns (uint8) { return _computeNextNumberOfTiers(claimCount); } /* ============ Internal Functions ============ */ /// @notice Computes how many tokens have been accounted for /// @return The balance of tokens that have been accounted for function _accountedBalance() internal view returns (uint256) { Observation memory obs = _totalAccumulator.observations[ DrawAccumulatorLib.newestDrawId(_totalAccumulator) ]; return (obs.available + obs.disbursed) + uint256(_directlyContributedReserve) - uint256(_totalWithdrawn); } /// @notice Returns the open draw ID based on the current block timestamp. /// @dev Returns `1` if the first draw hasn't opened yet. This prevents any contributions from /// going to the inaccessible draw zero. /// @dev First draw has an ID of `1`. This means that if `_lastAwardedDrawId` is zero, /// we know that no draws have been awarded yet. /// @return The ID of the draw period that the current block is in function _openDrawId() internal view returns (uint24) { uint48 _firstDrawOpensAt = firstDrawOpensAt; return (block.timestamp < _firstDrawOpensAt) ? 1 : (uint24((block.timestamp - _firstDrawOpensAt) / drawPeriodSeconds) + 1); } /// @notice Returns the next draw ID that can be awarded. /// @dev It's possible for draws to be missed, so the next draw ID to award /// may be more than one draw ahead of the last awarded draw ID. /// @return The next draw ID that can be awarded function _drawIdToAward() internal view returns (uint24) { uint24 openDrawId_ = _openDrawId(); return (openDrawId_ - _lastAwardedDrawId) > 1 ? openDrawId_ - 1 : openDrawId_; } /// @notice Returns the time at which a draw opens / opened at. /// @param drawId The draw to get the timestamp for /// @return The start time of the draw in seconds function _drawOpensAt(uint24 drawId) internal view returns (uint48) { return firstDrawOpensAt + (drawId - 1) * drawPeriodSeconds; } /// @notice Returns the time at which a draw closes / closed at. /// @param drawId The draw to get the timestamp for /// @return The end time of the draw in seconds function _drawClosesAt(uint24 drawId) internal view returns (uint48) { return firstDrawOpensAt + drawId * drawPeriodSeconds; } /// @notice Checks if the given draw is finalized. /// @param drawId The draw to check /// @return True if the draw is finalized, false otherwise function _isDrawFinalized(uint24 drawId) internal view returns (bool) { return block.timestamp >= _drawClosesAt(drawId + 1); } /// @notice Reverts if the given _tier is >= _numTiers /// @param _tier The tier to check /// @param _numTiers The current number of tiers function _checkValidTier(uint8 _tier, uint8 _numTiers) internal pure { if (_tier >= _numTiers) { revert InvalidTier(_tier, _numTiers); } } /// @notice Calculates the number of tiers given the number of prize claims /// @dev This function will use the claim count to determine the number of tiers, then add one for the canary tier. /// @param _claimCount The number of prize claims /// @return The estimated number of tiers + the canary tier function _computeNextNumberOfTiers(uint32 _claimCount) internal view returns (uint8) { // claimCount is expected to be the estimated number of claims for the current prize tier. return _estimateNumberOfTiersUsingPrizeCountPerDraw(_claimCount) + 1; } /// @notice Calculates the number of tiers given the number of prize claims /// @dev This function will use the claim count to determine the number of tiers, then add one for the canary tier. /// @param _claimCount The number of prize claims /// @return The estimated number of tiers + the canary tier function computeNextNumberOfTiers(uint32 _claimCount) external view returns (uint8) { return _computeNextNumberOfTiers(_claimCount); } /// @notice Returns the total prize tokens contributed between the given draw ids, inclusive. /// @dev Note that this is after smoothing is applied. /// @param _startDrawIdInclusive Start draw id inclusive /// @param _endDrawIdInclusive End draw id inclusive /// @return The total prize tokens contributed by all vaults function _getTotalContributedBetween( uint24 _startDrawIdInclusive, uint24 _endDrawIdInclusive ) internal view returns (uint256) { return DrawAccumulatorLib.getDisbursedBetween( _totalAccumulator, _startDrawIdInclusive, _endDrawIdInclusive, smoothing.intoSD59x18() ); } /** * @notice Transfers the given amount of prize tokens to the given address. * @param _to The address to transfer to * @param _amount The amount to transfer */ function _transfer(address _to, uint256 _amount) internal { _totalWithdrawn = SafeCast.toUint128(_totalWithdrawn + _amount); prizeToken.safeTransfer(_to, _amount); } /** * @notice Checks if the given user has won the prize for the specified tier in the given vault. * @param _drawId The draw ID for which to check the winner * @param _vault The address of the vault to check * @param _user The address of the user to check for the prize * @param _tier The tier for which the prize is to be checked * @param _prizeIndex The prize index to check. Must be less than prize count for the tier * @param _vaultPortion The portion of the prizes that were contributed by the given vault * @param _tierOdds The tier odds to apply to make prizes less frequent * @param _drawDuration The duration of prize accrual for the given tier * @return A boolean value indicating whether the user has won the prize or not */ function _isWinner( uint24 _drawId, address _vault, address _user, uint8 _tier, uint32 _prizeIndex, SD59x18 _vaultPortion, SD59x18 _tierOdds, uint24 _drawDuration ) internal view returns (bool) { uint32 tierPrizeCount = uint32(TierCalculationLib.prizeCount(_tier)); if (_prizeIndex >= tierPrizeCount) { revert InvalidPrizeIndex(_prizeIndex, tierPrizeCount, _tier); } uint256 userSpecificRandomNumber = TierCalculationLib.calculatePseudoRandomNumber( _drawId, _vault, _user, _tier, _prizeIndex, _winningRandomNumber ); (uint256 _userTwab, uint256 _vaultTwabTotalSupply) = _getVaultUserBalanceAndTotalSupplyTwab( _vault, _user, _drawDuration ); return TierCalculationLib.isWinner( userSpecificRandomNumber, _userTwab, _vaultTwabTotalSupply, _vaultPortion, _tierOdds ); } /** * @notice Computes the data needed for determining a winner of a prize from a specific vault for the last awarded draw. * @param _vault The address of the vault to check. * @param _tier The tier for which the prize is to be checked. * @param _numberOfTiers The number of tiers in the draw. * @param lastAwardedDrawId_ The ID of the last awarded draw. * @return vaultPortion The portion of the prizes that are going to this vault. * @return tierOdds The odds of winning the prize for the given tier. * @return drawDuration The duration of the draw. */ function _computeVaultTierDetails( address _vault, uint8 _tier, uint8 _numberOfTiers, uint24 lastAwardedDrawId_ ) internal view returns (SD59x18 vaultPortion, SD59x18 tierOdds, uint24 drawDuration) { if (lastAwardedDrawId_ == 0) { revert NoDrawsAwarded(); } _checkValidTier(_tier, _numberOfTiers); tierOdds = _tierOdds(_tier, _numberOfTiers); drawDuration = uint24(TierCalculationLib.estimatePrizeFrequencyInDraws(tierOdds)); vaultPortion = _getVaultPortion( _vault, SafeCast.toUint24( drawDuration > lastAwardedDrawId_ ? 1 : lastAwardedDrawId_ - drawDuration + 1 ), lastAwardedDrawId_ ); } /** * @notice Returns the time-weighted average balance (TWAB) and the TWAB total supply for the specified user in the given vault over a specified period. * @dev This function calculates the TWAB for a user by calling the getTwabBetween function of the TWAB controller for a specified period of time. * @param _vault The address of the vault for which to get the TWAB. * @param _user The address of the user for which to get the TWAB. * @param _drawDuration The duration of the period over which to calculate the TWAB, in number of draw periods. * @return twab The TWAB for the specified user in the given vault over the specified period. * @return twabTotalSupply The TWAB total supply over the specified period. */ function _getVaultUserBalanceAndTotalSupplyTwab( address _vault, address _user, uint256 _drawDuration ) internal view returns (uint256 twab, uint256 twabTotalSupply) { uint48 _endTimestamp = _drawClosesAt(_lastAwardedDrawId); uint48 _durationSeconds = SafeCast.toUint48(_drawDuration * drawPeriodSeconds); uint48 _startTimestamp = _endTimestamp > _durationSeconds ? _endTimestamp - _durationSeconds : 0; twab = twabController.getTwabBetween(_vault, _user, _startTimestamp, _endTimestamp); twabTotalSupply = twabController.getTotalSupplyTwabBetween( _vault, _startTimestamp, _endTimestamp ); } /** * @notice Calculates the portion of the vault's contribution to the prize pool over a specified duration in draws. * @param _vault The address of the vault for which to calculate the portion. * @param _startDrawId The starting draw ID (inclusive) of the draw range to calculate the contribution portion for. * @param _endDrawId The ending draw ID (inclusive) of the draw range to calculate the contribution portion for. * @return The portion of the vault's contribution to the prize pool over the specified duration in draws. */ function _getVaultPortion( address _vault, uint24 _startDrawId, uint24 _endDrawId ) internal view returns (SD59x18) { SD59x18 _smoothing = smoothing.intoSD59x18(); uint256 totalContributed = DrawAccumulatorLib.getDisbursedBetween( _totalAccumulator, _startDrawId, _endDrawId, _smoothing ); // vaultContributed / totalContributed return totalContributed != 0 ? sd( SafeCast.toInt256( DrawAccumulatorLib.getDisbursedBetween( _vaultAccumulator[_vault], _startDrawId, _endDrawId, _smoothing ) ) ).div(sd(SafeCast.toInt256(totalContributed))) : sd(0); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { SafeCast } from "openzeppelin/utils/math/SafeCast.sol"; import { TwabLib } from "./libraries/TwabLib.sol"; import { ObservationLib } from "./libraries/ObservationLib.sol"; /// @notice Emitted when an account already points to the same delegate address that is being set error SameDelegateAlreadySet(address delegate); /// @notice Emitted when an account tries to transfer to the sponsorship address error CannotTransferToSponsorshipAddress(); /// @notice Emitted when the period length is too short error PeriodLengthTooShort(); /// @notice Emitted when the period offset is not in the past. /// @param periodOffset The period offset that was passed in error PeriodOffsetInFuture(uint32 periodOffset); /// @notice Emitted when a user tries to mint or transfer to the zero address error TransferToZeroAddress(); // The minimum period length uint32 constant MINIMUM_PERIOD_LENGTH = 1 hours; // Allows users to revoke their chances to win by delegating to the sponsorship address. address constant SPONSORSHIP_ADDRESS = address(1); /** * @title PoolTogether V5 Time-Weighted Average Balance Controller * @author PoolTogether Inc. & G9 Software Inc. * @dev Time-Weighted Average Balance Controller for ERC20 tokens. * @notice This TwabController uses the TwabLib to provide token balances and on-chain historical lookups to a user(s) time-weighted average balance. Each user is mapped to an Account struct containing the TWAB history (ring buffer) and ring buffer parameters. Every token.transfer() creates a new TWAB observation. The new TWAB observation is stored in the circular ring buffer as either a new observation or rewriting a previous observation with new parameters. One observation per period is stored. The TwabLib guarantees minimum 1 year of search history if a period is a day. */ contract TwabController { using SafeCast for uint256; /// @notice Sets the minimum period length for Observations. When a period elapses, a new Observation is recorded, otherwise the most recent Observation is updated. uint32 public immutable PERIOD_LENGTH; /// @notice Sets the beginning timestamp for the first period. This allows us to maximize storage as well as line up periods with a chosen timestamp. /// @dev Ensure that the PERIOD_OFFSET is in the past. uint32 public immutable PERIOD_OFFSET; /* ============ State ============ */ /// @notice Record of token holders TWABs for each account for each vault. mapping(address => mapping(address => TwabLib.Account)) internal userObservations; /// @notice Record of tickets total supply and ring buff parameters used for observation. mapping(address => TwabLib.Account) internal totalSupplyObservations; /// @notice vault => user => delegate. mapping(address => mapping(address => address)) internal delegates; /* ============ Events ============ */ /** * @notice Emitted when a balance or delegateBalance is increased. * @param vault the vault for which the balance increased * @param user the users whose balance increased * @param amount the amount the balance increased by * @param delegateAmount the amount the delegateBalance increased by */ event IncreasedBalance( address indexed vault, address indexed user, uint96 amount, uint96 delegateAmount ); /** * @notice Emitted when a balance or delegateBalance is decreased. * @param vault the vault for which the balance decreased * @param user the users whose balance decreased * @param amount the amount the balance decreased by * @param delegateAmount the amount the delegateBalance decreased by */ event DecreasedBalance( address indexed vault, address indexed user, uint96 amount, uint96 delegateAmount ); /** * @notice Emitted when an Observation is recorded to the Ring Buffer. * @param vault the vault for which the Observation was recorded * @param user the users whose Observation was recorded * @param balance the resulting balance * @param delegateBalance the resulting delegated balance * @param isNew whether the observation is new or not * @param observation the observation that was created or updated */ event ObservationRecorded( address indexed vault, address indexed user, uint96 balance, uint96 delegateBalance, bool isNew, ObservationLib.Observation observation ); /** * @notice Emitted when a user delegates their balance to another address. * @param vault the vault for which the balance was delegated * @param delegator the user who delegated their balance * @param delegate the user who received the delegated balance */ event Delegated(address indexed vault, address indexed delegator, address indexed delegate); /** * @notice Emitted when the total supply or delegateTotalSupply is increased. * @param vault the vault for which the total supply increased * @param amount the amount the total supply increased by * @param delegateAmount the amount the delegateTotalSupply increased by */ event IncreasedTotalSupply(address indexed vault, uint96 amount, uint96 delegateAmount); /** * @notice Emitted when the total supply or delegateTotalSupply is decreased. * @param vault the vault for which the total supply decreased * @param amount the amount the total supply decreased by * @param delegateAmount the amount the delegateTotalSupply decreased by */ event DecreasedTotalSupply(address indexed vault, uint96 amount, uint96 delegateAmount); /** * @notice Emitted when a Total Supply Observation is recorded to the Ring Buffer. * @param vault the vault for which the Observation was recorded * @param balance the resulting balance * @param delegateBalance the resulting delegated balance * @param isNew whether the observation is new or not * @param observation the observation that was created or updated */ event TotalSupplyObservationRecorded( address indexed vault, uint96 balance, uint96 delegateBalance, bool isNew, ObservationLib.Observation observation ); /* ============ Constructor ============ */ /** * @notice Construct a new TwabController. * @dev Reverts if the period offset is in the future. * @param _periodLength Sets the minimum period length for Observations. When a period elapses, a new Observation * is recorded, otherwise the most recent Observation is updated. * @param _periodOffset Sets the beginning timestamp for the first period. This allows us to maximize storage as well * as line up periods with a chosen timestamp. */ constructor(uint32 _periodLength, uint32 _periodOffset) { if (_periodLength < MINIMUM_PERIOD_LENGTH) { revert PeriodLengthTooShort(); } if (_periodOffset > block.timestamp) { revert PeriodOffsetInFuture(_periodOffset); } PERIOD_LENGTH = _periodLength; PERIOD_OFFSET = _periodOffset; } /* ============ External Read Functions ============ */ /** * @notice Loads the current TWAB Account data for a specific vault stored for a user. * @dev Note this is a very expensive function * @param vault the vault for which the data is being queried * @param user the user whose data is being queried * @return The current TWAB Account data of the user */ function getAccount(address vault, address user) external view returns (TwabLib.Account memory) { return userObservations[vault][user]; } /** * @notice Loads the current total supply TWAB Account data for a specific vault. * @dev Note this is a very expensive function * @param vault the vault for which the data is being queried * @return The current total supply TWAB Account data */ function getTotalSupplyAccount(address vault) external view returns (TwabLib.Account memory) { return totalSupplyObservations[vault]; } /** * @notice The current token balance of a user for a specific vault. * @param vault the vault for which the balance is being queried * @param user the user whose balance is being queried * @return The current token balance of the user */ function balanceOf(address vault, address user) external view returns (uint256) { return userObservations[vault][user].details.balance; } /** * @notice The total supply of tokens for a vault. * @param vault the vault for which the total supply is being queried * @return The total supply of tokens for a vault */ function totalSupply(address vault) external view returns (uint256) { return totalSupplyObservations[vault].details.balance; } /** * @notice The total delegated amount of tokens for a vault. * @dev Delegated balance is not 1:1 with the token total supply. Users may delegate their * balance to the sponsorship address, which will result in those tokens being subtracted * from the total. * @param vault the vault for which the total delegated supply is being queried * @return The total delegated amount of tokens for a vault */ function totalSupplyDelegateBalance(address vault) external view returns (uint256) { return totalSupplyObservations[vault].details.delegateBalance; } /** * @notice The current delegate of a user for a specific vault. * @param vault the vault for which the delegate balance is being queried * @param user the user whose delegate balance is being queried * @return The current delegate balance of the user */ function delegateOf(address vault, address user) external view returns (address) { return _delegateOf(vault, user); } /** * @notice The current delegateBalance of a user for a specific vault. * @dev the delegateBalance is the sum of delegated balance to this user * @param vault the vault for which the delegateBalance is being queried * @param user the user whose delegateBalance is being queried * @return The current delegateBalance of the user */ function delegateBalanceOf(address vault, address user) external view returns (uint256) { return userObservations[vault][user].details.delegateBalance; } /** * @notice Looks up a users balance at a specific time in the past. * @param vault the vault for which the balance is being queried * @param user the user whose balance is being queried * @param periodEndOnOrAfterTime The time in the past for which the balance is being queried. The time will be snapped to a period end time on or after the timestamp. * @return The balance of the user at the target time */ function getBalanceAt( address vault, address user, uint256 periodEndOnOrAfterTime ) external view returns (uint256) { TwabLib.Account storage _account = userObservations[vault][user]; return TwabLib.getBalanceAt( PERIOD_LENGTH, PERIOD_OFFSET, _account.observations, _account.details, _periodEndOnOrAfter(periodEndOnOrAfterTime) ); } /** * @notice Looks up the total supply at a specific time in the past. * @param vault the vault for which the total supply is being queried * @param periodEndOnOrAfterTime The time in the past for which the balance is being queried. The time will be snapped to a period end time on or after the timestamp. * @return The total supply at the target time */ function getTotalSupplyAt( address vault, uint256 periodEndOnOrAfterTime ) external view returns (uint256) { TwabLib.Account storage _account = totalSupplyObservations[vault]; return TwabLib.getBalanceAt( PERIOD_LENGTH, PERIOD_OFFSET, _account.observations, _account.details, _periodEndOnOrAfter(periodEndOnOrAfterTime) ); } /** * @notice Looks up the average balance of a user between two timestamps. * @dev Timestamps are Unix timestamps denominated in seconds * @param vault the vault for which the average balance is being queried * @param user the user whose average balance is being queried * @param startTime the start of the time range for which the average balance is being queried. The time will be snapped to a period end time on or after the timestamp. * @param endTime the end of the time range for which the average balance is being queried. The time will be snapped to a period end time on or after the timestamp. * @return The average balance of the user between the two timestamps */ function getTwabBetween( address vault, address user, uint256 startTime, uint256 endTime ) external view returns (uint256) { TwabLib.Account storage _account = userObservations[vault][user]; // We snap the timestamps to the period end on or after the timestamp because the total supply records will be sparsely populated. // if two users update during a period, then the total supply observation will only exist for the last one. return TwabLib.getTwabBetween( PERIOD_LENGTH, PERIOD_OFFSET, _account.observations, _account.details, _periodEndOnOrAfter(startTime), _periodEndOnOrAfter(endTime) ); } /** * @notice Looks up the average total supply between two timestamps. * @dev Timestamps are Unix timestamps denominated in seconds * @param vault the vault for which the average total supply is being queried * @param startTime the start of the time range for which the average total supply is being queried * @param endTime the end of the time range for which the average total supply is being queried * @return The average total supply between the two timestamps */ function getTotalSupplyTwabBetween( address vault, uint256 startTime, uint256 endTime ) external view returns (uint256) { TwabLib.Account storage _account = totalSupplyObservations[vault]; // We snap the timestamps to the period end on or after the timestamp because the total supply records will be sparsely populated. // if two users update during a period, then the total supply observation will only exist for the last one. return TwabLib.getTwabBetween( PERIOD_LENGTH, PERIOD_OFFSET, _account.observations, _account.details, _periodEndOnOrAfter(startTime), _periodEndOnOrAfter(endTime) ); } /** * @notice Computes the period end timestamp on or after the given timestamp. * @param _timestamp The timestamp to check * @return The end timestamp of the period that ends on or immediately after the given timestamp */ function periodEndOnOrAfter(uint256 _timestamp) external view returns (uint256) { return _periodEndOnOrAfter(_timestamp); } /** * @notice Computes the period end timestamp on or after the given timestamp. * @param _timestamp The timestamp to compute the period end time for * @return A period end time. */ function _periodEndOnOrAfter(uint256 _timestamp) internal view returns (uint256) { if (_timestamp < PERIOD_OFFSET) { return PERIOD_OFFSET; } if ((_timestamp - PERIOD_OFFSET) % PERIOD_LENGTH == 0) { return _timestamp; } uint256 period = TwabLib.getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, _timestamp); return TwabLib.getPeriodEndTime(PERIOD_LENGTH, PERIOD_OFFSET, period); } /** * @notice Looks up the newest observation for a user. * @param vault the vault for which the observation is being queried * @param user the user whose observation is being queried * @return index The index of the observation * @return observation The observation of the user */ function getNewestObservation( address vault, address user ) external view returns (uint16, ObservationLib.Observation memory) { TwabLib.Account storage _account = userObservations[vault][user]; return TwabLib.getNewestObservation(_account.observations, _account.details); } /** * @notice Looks up the oldest observation for a user. * @param vault the vault for which the observation is being queried * @param user the user whose observation is being queried * @return index The index of the observation * @return observation The observation of the user */ function getOldestObservation( address vault, address user ) external view returns (uint16, ObservationLib.Observation memory) { TwabLib.Account storage _account = userObservations[vault][user]; return TwabLib.getOldestObservation(_account.observations, _account.details); } /** * @notice Looks up the newest total supply observation for a vault. * @param vault the vault for which the observation is being queried * @return index The index of the observation * @return observation The total supply observation */ function getNewestTotalSupplyObservation( address vault ) external view returns (uint16, ObservationLib.Observation memory) { TwabLib.Account storage _account = totalSupplyObservations[vault]; return TwabLib.getNewestObservation(_account.observations, _account.details); } /** * @notice Looks up the oldest total supply observation for a vault. * @param vault the vault for which the observation is being queried * @return index The index of the observation * @return observation The total supply observation */ function getOldestTotalSupplyObservation( address vault ) external view returns (uint16, ObservationLib.Observation memory) { TwabLib.Account storage _account = totalSupplyObservations[vault]; return TwabLib.getOldestObservation(_account.observations, _account.details); } /** * @notice Calculates the period a timestamp falls into. * @param time The timestamp to check * @return period The period the timestamp falls into */ function getTimestampPeriod(uint256 time) external view returns (uint256) { return TwabLib.getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, time); } /** * @notice Checks if the given timestamp is before the current overwrite period. * @param time The timestamp to check * @return True if the given time is finalized, false if it's during the current overwrite period. */ function hasFinalized(uint256 time) external view returns (bool) { return TwabLib.hasFinalized(PERIOD_LENGTH, PERIOD_OFFSET, time); } /** * @notice Computes the timestamp at which the current overwrite period started. * @dev The overwrite period is the period during which observations are collated. * @return period The timestamp at which the current overwrite period started. */ function currentOverwritePeriodStartedAt() external view returns (uint256) { return TwabLib.currentOverwritePeriodStartedAt(PERIOD_LENGTH, PERIOD_OFFSET); } /* ============ External Write Functions ============ */ /** * @notice Mints new balance and delegateBalance for a given user. * @dev Note that if the provided user to mint to is delegating that the delegate's * delegateBalance will be updated. * @dev Mint is expected to be called by the Vault. * @param _to The address to mint balance and delegateBalance to * @param _amount The amount to mint */ function mint(address _to, uint96 _amount) external { if (_to == address(0)) { revert TransferToZeroAddress(); } _transferBalance(msg.sender, address(0), _to, _amount); } /** * @notice Burns balance and delegateBalance for a given user. * @dev Note that if the provided user to burn from is delegating that the delegate's * delegateBalance will be updated. * @dev Burn is expected to be called by the Vault. * @param _from The address to burn balance and delegateBalance from * @param _amount The amount to burn */ function burn(address _from, uint96 _amount) external { _transferBalance(msg.sender, _from, address(0), _amount); } /** * @notice Transfers balance and delegateBalance from a given user. * @dev Note that if the provided user to transfer from is delegating that the delegate's * delegateBalance will be updated. * @param _from The address to transfer the balance and delegateBalance from * @param _to The address to transfer balance and delegateBalance to * @param _amount The amount to transfer */ function transfer(address _from, address _to, uint96 _amount) external { if (_to == address(0)) { revert TransferToZeroAddress(); } _transferBalance(msg.sender, _from, _to, _amount); } /** * @notice Sets a delegate for a user which forwards the delegateBalance tied to the user's * balance to the delegate's delegateBalance. * @param _vault The vault for which the delegate is being set * @param _to the address to delegate to */ function delegate(address _vault, address _to) external { _delegate(_vault, msg.sender, _to); } /** * @notice Delegate user balance to the sponsorship address. * @dev Must only be called by the Vault contract. * @param _from Address of the user delegating their balance to the sponsorship address. */ function sponsor(address _from) external { _delegate(msg.sender, _from, SPONSORSHIP_ADDRESS); } /* ============ Internal Functions ============ */ /** * @notice Transfers a user's vault balance from one address to another. * @dev If the user is delegating, their delegate's delegateBalance is also updated. * @dev If we are minting or burning tokens then the total supply is also updated. * @param _vault the vault for which the balance is being transferred * @param _from the address from which the balance is being transferred * @param _to the address to which the balance is being transferred * @param _amount the amount of balance being transferred */ function _transferBalance(address _vault, address _from, address _to, uint96 _amount) internal { if (_to == SPONSORSHIP_ADDRESS) { revert CannotTransferToSponsorshipAddress(); } if (_from == _to) { return; } // If we are transferring tokens from a delegated account to an undelegated account address _fromDelegate = _delegateOf(_vault, _from); address _toDelegate = _delegateOf(_vault, _to); if (_from != address(0)) { bool _isFromDelegate = _fromDelegate == _from; _decreaseBalances(_vault, _from, _amount, _isFromDelegate ? _amount : 0); // If the user is not delegating to themself, decrease the delegate's delegateBalance // If the user is delegating to the sponsorship address, don't adjust the delegateBalance if (!_isFromDelegate && _fromDelegate != SPONSORSHIP_ADDRESS) { _decreaseBalances(_vault, _fromDelegate, 0, _amount); } // Burn balance if we're transferring to address(0) // Burn delegateBalance if we're transferring to address(0) and burning from an address that is not delegating to the sponsorship address // Burn delegateBalance if we're transferring to an address delegating to the sponsorship address from an address that isn't delegating to the sponsorship address if ( _to == address(0) || (_toDelegate == SPONSORSHIP_ADDRESS && _fromDelegate != SPONSORSHIP_ADDRESS) ) { // If the user is delegating to the sponsorship address, don't adjust the total supply delegateBalance _decreaseTotalSupplyBalances( _vault, _to == address(0) ? _amount : 0, (_to == address(0) && _fromDelegate != SPONSORSHIP_ADDRESS) || (_toDelegate == SPONSORSHIP_ADDRESS && _fromDelegate != SPONSORSHIP_ADDRESS) ? _amount : 0 ); } } // If we are transferring tokens to an address other than address(0) if (_to != address(0)) { bool _isToDelegate = _toDelegate == _to; // If the user is delegating to themself, increase their delegateBalance _increaseBalances(_vault, _to, _amount, _isToDelegate ? _amount : 0); // Otherwise, increase their delegates delegateBalance if it is not the sponsorship address if (!_isToDelegate && _toDelegate != SPONSORSHIP_ADDRESS) { _increaseBalances(_vault, _toDelegate, 0, _amount); } // Mint balance if we're transferring from address(0) // Mint delegateBalance if we're transferring from address(0) and to an address not delegating to the sponsorship address // Mint delegateBalance if we're transferring from an address delegating to the sponsorship address to an address that isn't delegating to the sponsorship address if ( _from == address(0) || (_fromDelegate == SPONSORSHIP_ADDRESS && _toDelegate != SPONSORSHIP_ADDRESS) ) { _increaseTotalSupplyBalances( _vault, _from == address(0) ? _amount : 0, (_from == address(0) && _toDelegate != SPONSORSHIP_ADDRESS) || (_fromDelegate == SPONSORSHIP_ADDRESS && _toDelegate != SPONSORSHIP_ADDRESS) ? _amount : 0 ); } } } /** * @notice Looks up the delegate of a user. * @param _vault the vault for which the user's delegate is being queried * @param _user the address to query the delegate of * @return The address of the user's delegate */ function _delegateOf(address _vault, address _user) internal view returns (address) { address _userDelegate; if (_user != address(0)) { _userDelegate = delegates[_vault][_user]; // If the user has not delegated, then the user is the delegate if (_userDelegate == address(0)) { _userDelegate = _user; } } return _userDelegate; } /** * @notice Transfers a user's vault delegateBalance from one address to another. * @param _vault the vault for which the delegateBalance is being transferred * @param _fromDelegate the address from which the delegateBalance is being transferred * @param _toDelegate the address to which the delegateBalance is being transferred * @param _amount the amount of delegateBalance being transferred */ function _transferDelegateBalance( address _vault, address _fromDelegate, address _toDelegate, uint96 _amount ) internal { // If we are transferring tokens from a delegated account to an undelegated account if (_fromDelegate != address(0) && _fromDelegate != SPONSORSHIP_ADDRESS) { _decreaseBalances(_vault, _fromDelegate, 0, _amount); // If we are delegating to the zero address, decrease total supply // If we are delegating to the sponsorship address, decrease total supply if (_toDelegate == address(0) || _toDelegate == SPONSORSHIP_ADDRESS) { _decreaseTotalSupplyBalances(_vault, 0, _amount); } } // If we are transferring tokens from an undelegated account to a delegated account if (_toDelegate != address(0) && _toDelegate != SPONSORSHIP_ADDRESS) { _increaseBalances(_vault, _toDelegate, 0, _amount); // If we are removing delegation from the zero address, increase total supply // If we are removing delegation from the sponsorship address, increase total supply if (_fromDelegate == address(0) || _fromDelegate == SPONSORSHIP_ADDRESS) { _increaseTotalSupplyBalances(_vault, 0, _amount); } } } /** * @notice Sets a delegate for a user which forwards the delegateBalance tied to the user's * balance to the delegate's delegateBalance. "Sponsoring" means the funds aren't delegated * to anyone; this can be done by passing address(0) or the SPONSORSHIP_ADDRESS as the delegate. * @param _vault The vault for which the delegate is being set * @param _from the address to delegate from * @param _to the address to delegate to */ function _delegate(address _vault, address _from, address _to) internal { address _currentDelegate = _delegateOf(_vault, _from); // address(0) is interpreted as sponsoring, so they don't need to know the sponsorship address. address to = _to == address(0) ? SPONSORSHIP_ADDRESS : _to; if (to == _currentDelegate) { revert SameDelegateAlreadySet(to); } delegates[_vault][_from] = to; _transferDelegateBalance( _vault, _currentDelegate, _to, SafeCast.toUint96(userObservations[_vault][_from].details.balance) ); emit Delegated(_vault, _from, to); } /** * @notice Increases a user's balance and delegateBalance for a specific vault. * @param _vault the vault for which the balance is being increased * @param _user the address of the user whose balance is being increased * @param _amount the amount of balance being increased * @param _delegateAmount the amount of delegateBalance being increased */ function _increaseBalances( address _vault, address _user, uint96 _amount, uint96 _delegateAmount ) internal { TwabLib.Account storage _account = userObservations[_vault][_user]; ( ObservationLib.Observation memory _observation, bool _isNewObservation, bool _isObservationRecorded, TwabLib.AccountDetails memory accountDetails ) = TwabLib.increaseBalances(PERIOD_LENGTH, PERIOD_OFFSET, _account, _amount, _delegateAmount); // Always emit the balance change event if (_amount != 0 || _delegateAmount != 0) { emit IncreasedBalance(_vault, _user, _amount, _delegateAmount); } // Conditionally emit the observation recorded event if (_isObservationRecorded) { emit ObservationRecorded( _vault, _user, accountDetails.balance, accountDetails.delegateBalance, _isNewObservation, _observation ); } } /** * @notice Decreases the a user's balance and delegateBalance for a specific vault. * @param _vault the vault for which the totalSupply balance is being decreased * @param _amount the amount of balance being decreased * @param _delegateAmount the amount of delegateBalance being decreased */ function _decreaseBalances( address _vault, address _user, uint96 _amount, uint96 _delegateAmount ) internal { TwabLib.Account storage _account = userObservations[_vault][_user]; ( ObservationLib.Observation memory _observation, bool _isNewObservation, bool _isObservationRecorded, TwabLib.AccountDetails memory accountDetails ) = TwabLib.decreaseBalances( PERIOD_LENGTH, PERIOD_OFFSET, _account, _amount, _delegateAmount, "TC/observation-burn-lt-delegate-balance" ); // Always emit the balance change event if (_amount != 0 || _delegateAmount != 0) { emit DecreasedBalance(_vault, _user, _amount, _delegateAmount); } // Conditionally emit the observation recorded event if (_isObservationRecorded) { emit ObservationRecorded( _vault, _user, accountDetails.balance, accountDetails.delegateBalance, _isNewObservation, _observation ); } } /** * @notice Decreases the totalSupply balance and delegateBalance for a specific vault. * @param _vault the vault for which the totalSupply balance is being decreased * @param _amount the amount of balance being decreased * @param _delegateAmount the amount of delegateBalance being decreased */ function _decreaseTotalSupplyBalances( address _vault, uint96 _amount, uint96 _delegateAmount ) internal { TwabLib.Account storage _account = totalSupplyObservations[_vault]; ( ObservationLib.Observation memory _observation, bool _isNewObservation, bool _isObservationRecorded, TwabLib.AccountDetails memory accountDetails ) = TwabLib.decreaseBalances( PERIOD_LENGTH, PERIOD_OFFSET, _account, _amount, _delegateAmount, "TC/burn-amount-exceeds-total-supply-balance" ); // Always emit the balance change event if (_amount != 0 || _delegateAmount != 0) { emit DecreasedTotalSupply(_vault, _amount, _delegateAmount); } // Conditionally emit the observation recorded event if (_isObservationRecorded) { emit TotalSupplyObservationRecorded( _vault, accountDetails.balance, accountDetails.delegateBalance, _isNewObservation, _observation ); } } /** * @notice Increases the totalSupply balance and delegateBalance for a specific vault. * @param _vault the vault for which the totalSupply balance is being increased * @param _amount the amount of balance being increased * @param _delegateAmount the amount of delegateBalance being increased */ function _increaseTotalSupplyBalances( address _vault, uint96 _amount, uint96 _delegateAmount ) internal { TwabLib.Account storage _account = totalSupplyObservations[_vault]; ( ObservationLib.Observation memory _observation, bool _isNewObservation, bool _isObservationRecorded, TwabLib.AccountDetails memory accountDetails ) = TwabLib.increaseBalances(PERIOD_LENGTH, PERIOD_OFFSET, _account, _amount, _delegateAmount); // Always emit the balance change event if (_amount != 0 || _delegateAmount != 0) { emit IncreasedTotalSupply(_vault, _amount, _delegateAmount); } // Conditionally emit the observation recorded event if (_isObservationRecorded) { emit TotalSupplyObservationRecorded( _vault, accountDetails.balance, accountDetails.delegateBalance, _isNewObservation, _observation ); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; /** * @title PoolTogether V5 Claimable Interface * @author G9 Software Inc. * @notice Provides a concise and consistent interface for Claimer contracts to interact with Vaults * in PoolTogether V5. */ interface IClaimable { /** * @notice Emitted when a new claimer has been set * @dev This event MUST be emitted when a new claimer has been set. * @param claimer Address of the new claimer */ event ClaimerSet(address indexed claimer); /** * @notice Claim a prize for a winner * @param _winner The winner of the prize * @param _tier The prize tier * @param _prizeIndex The prize index * @param _fee The fee to charge, in prize tokens * @param _feeRecipient The recipient of the fee * @return The total prize token amount claimed (zero if already claimed) */ function claimPrize( address _winner, uint8 _tier, uint32 _prizeIndex, uint96 _fee, address _feeRecipient ) external returns (uint256); /** * @notice Gets the current address that can call `claimPrize`. * @return The claimer address */ function claimer() external returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; struct VaultHooks { /// @notice If true, the vault will call the beforeClaimPrize hook on the implementation bool useBeforeClaimPrize; /// @notice If true, the vault will call the afterClaimPrize hook on the implementation bool useAfterClaimPrize; /// @notice The address of the smart contract implementing the hooks IVaultHooks implementation; } /** * @title PoolTogether V5 Vault Hooks Interface * @author PoolTogether Inc. & G9 Software Inc. * @notice Allows winners to attach smart contract hooks to their prize winnings */ interface IVaultHooks { /** * @notice Triggered before the prize pool claim prize function is called. * @param winner The user who won the prize and for whom this hook is attached * @param tier The tier of the prize * @param prizeIndex The index of the prize in the tier * @param fee The fee portion of the prize that will be allocated to the claimer * @param feeRecipient The recipient of the claim fee * @return address The address of the recipient of the prize */ function beforeClaimPrize( address winner, uint8 tier, uint32 prizeIndex, uint96 fee, address feeRecipient ) external returns (address); /** * @notice Triggered after the prize pool claim prize function is called. * @param winner The user who won the prize and for whom this hook is attached * @param tier The tier of the prize * @param prizeIndex The index of the prize * @param prize The total size of the prize (payout + fee) * @param recipient The recipient of the prize */ function afterClaimPrize( address winner, uint8 tier, uint32 prizeIndex, uint256 prize, address recipient ) external; }
// 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: 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 (last updated v4.9.4) (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; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.4) (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. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. * * CAUTION: See Security Considerations above. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated 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 // 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: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.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 "./sd1x18/Casting.sol"; import "./sd1x18/Constants.sol"; import "./sd1x18/Errors.sol"; import "./sd1x18/ValueType.sol";
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { UD60x18 } from "prb-math/UD60x18.sol"; type UD34x4 is uint128; /// @notice Emitted when converting a basic integer to the fixed-point format overflows UD34x4. error PRBMath_UD34x4_Convert_Overflow(uint128 x); error PRBMath_UD34x4_fromUD60x18_Convert_Overflow(uint256 x); /// @dev The maximum value an UD34x4 number can have. uint128 constant uMAX_UD34x4 = 340282366920938463463374607431768211455; uint128 constant uUNIT = 1e4; /// @notice Casts an UD34x4 number into UD60x18. /// @dev Requirements: /// - x must be less than or equal to `uMAX_UD2x18`. function intoUD60x18(UD34x4 x) pure returns (UD60x18) { return UD60x18.wrap(uint256(UD34x4.unwrap(x)) * uint256(1e14)); } /// @notice Casts an UD60x18 number into UD34x4 /// @dev Requirements: /// - x must be less than or equal to `uMAX_UD34x4`. /// @param x The value to be converted /// @return The value as UD34x4 function fromUD60x18(UD60x18 x) pure returns (UD34x4) { uint256 xUint = UD60x18.unwrap(x) / 1e14; if (xUint > uMAX_UD34x4) { revert PRBMath_UD34x4_fromUD60x18_Convert_Overflow(x.unwrap()); } return UD34x4.wrap(uint128(xUint)); } /// @notice Converts an UD34x4 number to a simple integer by dividing it by `UNIT`. Rounds towards zero in the process. /// @dev Rounds down in the process. /// @param x The UD34x4 number to convert. /// @return result The same number in basic integer form. function convert(UD34x4 x) pure returns (uint128 result) { result = UD34x4.unwrap(x) / uUNIT; } /// @notice Converts a simple integer to UD34x4 by multiplying it by `UNIT`. /// /// @dev Requirements: /// - x must be less than or equal to `MAX_UD34x4` divided by `UNIT`. /// /// @param x The basic integer to convert. /// @param result The same number converted to UD34x4. function convert(uint128 x) pure returns (UD34x4 result) { if (x > uMAX_UD34x4 / uUNIT) { revert PRBMath_UD34x4_Convert_Overflow(x); } unchecked { result = UD34x4.wrap(x * uUNIT); } } /// @notice Alias for the `convert` function defined above. function fromUD34x4(UD34x4 x) pure returns (uint128 result) { result = convert(x); } /// @notice Alias for the `convert` function defined above. function toUD34x4(uint128 x) pure returns (UD34x4 result) { result = convert(x); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { SafeCast } from "openzeppelin/utils/math/SafeCast.sol"; import { RingBufferLib } from "ring-buffer-lib/RingBufferLib.sol"; import { SD59x18, sd, unwrap, convert } from "prb-math/SD59x18.sol"; /// @notice Emitted when adding balance for draw zero. error AddToDrawZero(); /// @notice Emitted when an action can't be done on a closed draw. /// @param drawId The ID of the closed draw /// @param newestDrawId The newest draw ID error DrawAwarded(uint24 drawId, uint24 newestDrawId); /// @notice Emitted when a draw range is not strictly increasing. /// @param startDrawId The start draw ID of the range /// @param endDrawId The end draw ID of the range error InvalidDrawRange(uint24 startDrawId, uint24 endDrawId); struct Observation { uint96 available; // track the total amount available as of this Observation uint160 disbursed; // track the total accumulated previously } /// @title Draw Accumulator Lib /// @author G9 Software Inc. /// @notice This contract distributes tokens over time according to an exponential weighted average. Time is divided into discrete "draws", of which each is allocated tokens. library DrawAccumulatorLib { /// @notice The maximum number of observations that can be recorded. uint16 internal constant MAX_CARDINALITY = 366; /// @notice The metadata for using the ring buffer. struct RingBufferInfo { uint16 nextIndex; uint16 cardinality; } /// @notice An accumulator for a draw. struct Accumulator { RingBufferInfo ringBufferInfo; uint24[366] drawRingBuffer; mapping(uint256 drawId => Observation observation) observations; } /// @notice A pair of uint24s. struct Pair48 { uint24 first; uint24 second; } /// @notice Adds balance for the given draw id to the accumulator. /// @param accumulator The accumulator to add to /// @param _amount The amount of balance to add /// @param _drawId The draw id to which to add balance to. This must be greater than or equal to the previous addition's draw id. /// @param _alpha The alpha value to use for the exponential weighted average. /// @return True if a new observation was created, false otherwise. function add( Accumulator storage accumulator, uint256 _amount, uint24 _drawId, SD59x18 _alpha ) internal returns (bool) { if (_drawId == 0) { revert AddToDrawZero(); } RingBufferInfo memory ringBufferInfo = accumulator.ringBufferInfo; uint24 newestDrawId_ = accumulator.drawRingBuffer[ RingBufferLib.newestIndex(ringBufferInfo.nextIndex, MAX_CARDINALITY) ]; if (_drawId < newestDrawId_) { revert DrawAwarded(_drawId, newestDrawId_); } mapping(uint256 drawId => Observation observation) storage accumulatorObservations = accumulator .observations; Observation memory newestObservation_ = accumulatorObservations[newestDrawId_]; if (_drawId != newestDrawId_) { uint256 relativeDraw = _drawId - newestDrawId_; uint256 remainingAmount = integrateInf(_alpha, relativeDraw, newestObservation_.available); uint256 disbursedAmount = integrate(_alpha, 0, relativeDraw, newestObservation_.available); uint16 cardinality = ringBufferInfo.cardinality; if (ringBufferInfo.cardinality < MAX_CARDINALITY) { cardinality += 1; } else { // Delete the old observation to save gas (older than 1 year) delete accumulatorObservations[accumulator.drawRingBuffer[ringBufferInfo.nextIndex]]; } accumulator.drawRingBuffer[ringBufferInfo.nextIndex] = _drawId; accumulatorObservations[_drawId] = Observation({ available: SafeCast.toUint96(_amount + remainingAmount), disbursed: SafeCast.toUint160( newestObservation_.disbursed + disbursedAmount + newestObservation_.available - (remainingAmount + disbursedAmount) ) }); accumulator.ringBufferInfo = RingBufferInfo({ nextIndex: uint16(RingBufferLib.nextIndex(ringBufferInfo.nextIndex, MAX_CARDINALITY)), cardinality: cardinality }); return true; } else { accumulatorObservations[newestDrawId_] = Observation({ available: SafeCast.toUint96(newestObservation_.available + _amount), disbursed: newestObservation_.disbursed }); return false; } } /// @notice Gets the total remaining balance after and including the given start draw id. This is the sum of all draw balances from start draw id to infinity. /// The start draw id must be greater than or equal to the newest draw id. /// @param accumulator The accumulator to sum /// @param _startDrawId The draw id to start summing from, inclusive /// @param _alpha The alpha value to use for the exponential weighted average /// @return The sum of draw balances from start draw to infinity function getTotalRemaining( Accumulator storage accumulator, uint24 _startDrawId, SD59x18 _alpha ) internal view returns (uint256) { RingBufferInfo memory ringBufferInfo = accumulator.ringBufferInfo; if (ringBufferInfo.cardinality == 0) { return 0; } uint24 newestDrawId_ = accumulator.drawRingBuffer[ RingBufferLib.newestIndex(ringBufferInfo.nextIndex, MAX_CARDINALITY) ]; if (_startDrawId < newestDrawId_) { revert DrawAwarded(_startDrawId, newestDrawId_); } return integrateInf( _alpha, _startDrawId - newestDrawId_, accumulator.observations[newestDrawId_].available ); } /// @notice Returns the newest draw id from the accumulator. /// @param accumulator The accumulator to get the newest draw id from /// @return The newest draw id function newestDrawId(Accumulator storage accumulator) internal view returns (uint256) { return accumulator.drawRingBuffer[ RingBufferLib.newestIndex(accumulator.ringBufferInfo.nextIndex, MAX_CARDINALITY) ]; } /// @notice Gets the balance that was disbursed between the given start and end draw ids, inclusive. /// @param _accumulator The accumulator to get the disbursed balance from /// @param _startDrawId The start draw id, inclusive /// @param _endDrawId The end draw id, inclusive /// @param _alpha The alpha value to use for the exponential weighted average /// @return The disbursed balance between the given start and end draw ids, inclusive function getDisbursedBetween( Accumulator storage _accumulator, uint24 _startDrawId, uint24 _endDrawId, SD59x18 _alpha ) internal view returns (uint256) { if (_startDrawId > _endDrawId) { revert InvalidDrawRange(_startDrawId, _endDrawId); } RingBufferInfo memory ringBufferInfo = _accumulator.ringBufferInfo; if (ringBufferInfo.cardinality == 0) { return 0; } Pair48 memory indexes = computeIndices(ringBufferInfo); Pair48 memory drawIds = readDrawIds(_accumulator, indexes); if (_endDrawId < drawIds.first) { return 0; } /** head: residual accrual from observation before start. (if any) body: if there is more than one observations between start and current, then take the past _accumulator diff tail: accrual between the newest observation and current. if card > 1 there is a tail (almost always) let: - s = start draw id - e = end draw id - o = observation - h = "head". residual balance from the last o occurring before s. head is the disbursed amount between (o, s) - t = "tail". the residual balance from the last o occurring before e. tail is the disbursed amount between (o, e) - b = "body". if there are *two* observations between s and e we calculate how much was disbursed. body is (last obs disbursed - first obs disbursed) total = head + body + tail lastObservationOccurringAtOrBeforeEnd firstObservationOccurringAtOrAfterStart Like so s e o <h> o <t> o s e o <h> o <b> o <t> o */ uint24 lastObservationDrawIdOccurringAtOrBeforeEnd; if (_endDrawId >= drawIds.second) { // then it must be the end lastObservationDrawIdOccurringAtOrBeforeEnd = drawIds.second; } else if (_endDrawId == drawIds.first) { // then it must be the first lastObservationDrawIdOccurringAtOrBeforeEnd = drawIds.first; } else if (_endDrawId == drawIds.second - 1) { // then it must be the one before the end // (we check this case since it is common and we want to avoid the extra binary search) lastObservationDrawIdOccurringAtOrBeforeEnd = _accumulator.drawRingBuffer[ uint16(RingBufferLib.offset(indexes.second, 1, ringBufferInfo.cardinality)) ]; } else { // The last obs before or at end must be between newest and oldest // binary search (, uint24 beforeOrAtDrawId, , uint24 afterOrAtDrawId) = binarySearch( _accumulator.drawRingBuffer, uint16(indexes.first), uint16(indexes.second), ringBufferInfo.cardinality, _endDrawId ); lastObservationDrawIdOccurringAtOrBeforeEnd = afterOrAtDrawId == _endDrawId ? afterOrAtDrawId : beforeOrAtDrawId; } uint24 observationDrawIdBeforeOrAtStart; uint24 firstObservationDrawIdOccurringAtOrAfterStart; // if there is only one observation, or startId is after the newest record if (_startDrawId >= drawIds.second) { // then use the newest record observationDrawIdBeforeOrAtStart = drawIds.second; } else if (_startDrawId <= drawIds.first) { // if the start is before the oldest record // then set to the oldest record. firstObservationDrawIdOccurringAtOrAfterStart = drawIds.first; } else { // The start must be between newest and oldest // binary search ( , observationDrawIdBeforeOrAtStart, , firstObservationDrawIdOccurringAtOrAfterStart ) = binarySearch( _accumulator.drawRingBuffer, uint16(indexes.first), uint16(indexes.second), ringBufferInfo.cardinality, _startDrawId ); } uint256 total; // if a "head" exists if ( observationDrawIdBeforeOrAtStart > 0 && firstObservationDrawIdOccurringAtOrAfterStart > 0 && observationDrawIdBeforeOrAtStart != lastObservationDrawIdOccurringAtOrBeforeEnd ) { Observation memory beforeOrAtStart = _accumulator.observations[ observationDrawIdBeforeOrAtStart ]; uint24 headStartDrawId = _startDrawId - observationDrawIdBeforeOrAtStart; total += integrate( _alpha, headStartDrawId, headStartDrawId + (firstObservationDrawIdOccurringAtOrAfterStart - _startDrawId), beforeOrAtStart.available ); } // if a "body" exists if ( firstObservationDrawIdOccurringAtOrAfterStart > 0 && firstObservationDrawIdOccurringAtOrAfterStart < lastObservationDrawIdOccurringAtOrBeforeEnd ) { Observation memory atOrAfterStart = _accumulator.observations[ firstObservationDrawIdOccurringAtOrAfterStart ]; total += _accumulator.observations[lastObservationDrawIdOccurringAtOrBeforeEnd].disbursed - atOrAfterStart.disbursed; } total += computeTail( _accumulator, _startDrawId, _endDrawId, lastObservationDrawIdOccurringAtOrBeforeEnd, _alpha ); return total; } /// @notice Computes the "tail" for the given accumulator and range. The tail is the residual balance from the last observation occurring before the end draw id. /// @param accumulator The accumulator to compute for /// @param _startDrawId The start draw id, inclusive /// @param _endDrawId The end draw id, inclusive /// @param _lastObservationDrawIdOccurringAtOrBeforeEnd The last observation draw id occurring at or before the end draw id /// @return The total balance of the tail of the range. function computeTail( Accumulator storage accumulator, uint24 _startDrawId, uint24 _endDrawId, uint24 _lastObservationDrawIdOccurringAtOrBeforeEnd, SD59x18 _alpha ) internal view returns (uint256) { return integrate( _alpha, ( _startDrawId > _lastObservationDrawIdOccurringAtOrBeforeEnd ? _startDrawId : _lastObservationDrawIdOccurringAtOrBeforeEnd ) - _lastObservationDrawIdOccurringAtOrBeforeEnd, _endDrawId - _lastObservationDrawIdOccurringAtOrBeforeEnd + 1, accumulator.observations[_lastObservationDrawIdOccurringAtOrBeforeEnd].available ); } /// @notice Computes the first and last indices of observations for the given ring buffer info. /// @param ringBufferInfo The ring buffer info to compute for /// @return A pair of indices, where the first is the oldest index and the second is the newest index function computeIndices( RingBufferInfo memory ringBufferInfo ) internal pure returns (Pair48 memory) { return Pair48({ first: uint16( RingBufferLib.oldestIndex( ringBufferInfo.nextIndex, ringBufferInfo.cardinality, MAX_CARDINALITY ) ), second: uint16( RingBufferLib.newestIndex(ringBufferInfo.nextIndex, ringBufferInfo.cardinality) ) }); } /// @notice Retrieves the draw ids for the given accumulator observation indices. /// @param accumulator The accumulator to retrieve from /// @param indices The indices to retrieve /// @return A pair of draw ids, where the first is the draw id of the pair's first index and the second is the draw id of the pair's second index function readDrawIds( Accumulator storage accumulator, Pair48 memory indices ) internal view returns (Pair48 memory) { return Pair48({ first: accumulator.drawRingBuffer[indices.first], second: accumulator.drawRingBuffer[indices.second] }); } /// @notice Integrates from the given x to infinity for the exponential weighted average. /// @param _alpha The exponential weighted average smoothing parameter. /// @param _x The x value to integrate from. /// @param _k The k value to scale the sum (this is the total available balance). /// @return The integration from x to inf of the EWA for the given parameters. function integrateInf(SD59x18 _alpha, uint256 _x, uint256 _k) internal pure returns (uint256) { return uint256(convert(computeC(_alpha, _x, _k))); } /// @notice Integrates from the given start x to end x for the exponential weighted average. /// @param _alpha The exponential weighted average smoothing parameter. /// @param _start The x value to integrate from. /// @param _end The x value to integrate to /// @param _k The k value to scale the sum (this is the total available balance). /// @return The integration from start to end of the EWA for the given parameters. function integrate( SD59x18 _alpha, uint256 _start, uint256 _end, uint256 _k ) internal pure returns (uint256) { return uint256( convert(sd(unwrap(computeC(_alpha, _start, _k)) - unwrap(computeC(_alpha, _end, _k)))) ); } /// @notice Computes the interim value C for the EWA. /// @param _alpha The exponential weighted average smoothing parameter. /// @param _x The x value to compute for /// @param _k The total available balance /// @return The value C function computeC(SD59x18 _alpha, uint256 _x, uint256 _k) internal pure returns (SD59x18) { return convert(int(_k)).mul(_alpha.pow(convert(int256(_x)))); } /// @notice Binary searches an array of draw ids for the given target draw id. /// @dev The _targetDrawId MUST exist between the range of draws at _oldestIndex and _newestIndex (inclusive) /// @param _drawRingBuffer The array of draw ids to search /// @param _oldestIndex The oldest index in the ring buffer /// @param _newestIndex The newest index in the ring buffer /// @param _cardinality The number of items in the ring buffer /// @param _targetDrawId The target draw id to search for /// @return beforeOrAtIndex The index of the observation occurring at or before the target draw id /// @return beforeOrAtDrawId The draw id of the observation occurring at or before the target draw id /// @return afterOrAtIndex The index of the observation occurring at or after the target draw id /// @return afterOrAtDrawId The draw id of the observation occurring at or after the target draw id function binarySearch( uint24[366] storage _drawRingBuffer, uint16 _oldestIndex, uint16 _newestIndex, uint16 _cardinality, uint24 _targetDrawId ) internal view returns ( uint16 beforeOrAtIndex, uint24 beforeOrAtDrawId, uint16 afterOrAtIndex, uint24 afterOrAtDrawId ) { uint16 leftSide = _oldestIndex; uint16 rightSide = _newestIndex < leftSide ? leftSide + _cardinality - 1 : _newestIndex; uint16 currentIndex; while (true) { // We start our search in the middle of the `leftSide` and `rightSide`. // After each iteration, we narrow down the search to the left or the right side while still starting our search in the middle. currentIndex = (leftSide + rightSide) / 2; beforeOrAtIndex = uint16(RingBufferLib.wrap(currentIndex, _cardinality)); beforeOrAtDrawId = _drawRingBuffer[beforeOrAtIndex]; afterOrAtIndex = uint16(RingBufferLib.nextIndex(currentIndex, _cardinality)); afterOrAtDrawId = _drawRingBuffer[afterOrAtIndex]; bool targetAtOrAfter = beforeOrAtDrawId <= _targetDrawId; // Check if we've found the corresponding Observation. if (targetAtOrAfter && _targetDrawId <= afterOrAtDrawId) { break; } // If `beforeOrAtTimestamp` is greater than `_target`, then we keep searching lower. To the left of the current index. if (!targetAtOrAfter) { rightSide = currentIndex - 1; } else { // Otherwise, we keep searching higher. To the left of the current index. leftSide = currentIndex + 1; } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { SafeCast } from "openzeppelin/utils/math/SafeCast.sol"; import { SD59x18, sd } from "prb-math/SD59x18.sol"; import { UD60x18, ud, convert } from "prb-math/UD60x18.sol"; import { UD34x4, fromUD60x18 as fromUD60x18toUD34x4, intoUD60x18 as fromUD34x4toUD60x18 } from "../libraries/UD34x4.sol"; import { TierCalculationLib } from "../libraries/TierCalculationLib.sol"; /// @notice Struct that tracks tier liquidity information. struct Tier { uint24 drawId; uint104 prizeSize; UD34x4 prizeTokenPerShare; } /// @notice Emitted when the number of tiers is less than the minimum number of tiers. /// @param numTiers The invalid number of tiers error NumberOfTiersLessThanMinimum(uint8 numTiers); /// @notice Emitted when the number of tiers is greater than the max tiers /// @param numTiers The invalid number of tiers error NumberOfTiersGreaterThanMaximum(uint8 numTiers); /// @notice Emitted when there is insufficient liquidity to consume. /// @param requestedLiquidity The requested amount of liquidity error InsufficientLiquidity(uint104 requestedLiquidity); uint8 constant MINIMUM_NUMBER_OF_TIERS = 3; uint8 constant MAXIMUM_NUMBER_OF_TIERS = 10; /// @title Tiered Liquidity Distributor /// @author PoolTogether Inc. /// @notice A contract that distributes liquidity according to PoolTogether V5 distribution rules. contract TieredLiquidityDistributor { /* ============ Events ============ */ /// @notice Emitted when the reserve is consumed due to insufficient prize liquidity. /// @param amount The amount to decrease by event ReserveConsumed(uint256 amount); /* ============ Constants ============ */ /// @notice The odds for each tier and number of tiers pair. SD59x18 internal immutable TIER_ODDS_0; SD59x18 internal immutable TIER_ODDS_EVERY_DRAW; SD59x18 internal immutable TIER_ODDS_1_4; SD59x18 internal immutable TIER_ODDS_1_5; SD59x18 internal immutable TIER_ODDS_2_5; SD59x18 internal immutable TIER_ODDS_1_6; SD59x18 internal immutable TIER_ODDS_2_6; SD59x18 internal immutable TIER_ODDS_3_6; SD59x18 internal immutable TIER_ODDS_1_7; SD59x18 internal immutable TIER_ODDS_2_7; SD59x18 internal immutable TIER_ODDS_3_7; SD59x18 internal immutable TIER_ODDS_4_7; SD59x18 internal immutable TIER_ODDS_1_8; SD59x18 internal immutable TIER_ODDS_2_8; SD59x18 internal immutable TIER_ODDS_3_8; SD59x18 internal immutable TIER_ODDS_4_8; SD59x18 internal immutable TIER_ODDS_5_8; SD59x18 internal immutable TIER_ODDS_1_9; SD59x18 internal immutable TIER_ODDS_2_9; SD59x18 internal immutable TIER_ODDS_3_9; SD59x18 internal immutable TIER_ODDS_4_9; SD59x18 internal immutable TIER_ODDS_5_9; SD59x18 internal immutable TIER_ODDS_6_9; SD59x18 internal immutable TIER_ODDS_1_10; SD59x18 internal immutable TIER_ODDS_2_10; SD59x18 internal immutable TIER_ODDS_3_10; SD59x18 internal immutable TIER_ODDS_4_10; SD59x18 internal immutable TIER_ODDS_5_10; SD59x18 internal immutable TIER_ODDS_6_10; SD59x18 internal immutable TIER_ODDS_7_10; /// @notice The estimated number of prizes given X tiers. uint32 internal immutable ESTIMATED_PRIZES_PER_DRAW_FOR_3_TIERS; uint32 internal immutable ESTIMATED_PRIZES_PER_DRAW_FOR_4_TIERS; uint32 internal immutable ESTIMATED_PRIZES_PER_DRAW_FOR_5_TIERS; uint32 internal immutable ESTIMATED_PRIZES_PER_DRAW_FOR_6_TIERS; uint32 internal immutable ESTIMATED_PRIZES_PER_DRAW_FOR_7_TIERS; uint32 internal immutable ESTIMATED_PRIZES_PER_DRAW_FOR_8_TIERS; uint32 internal immutable ESTIMATED_PRIZES_PER_DRAW_FOR_9_TIERS; uint32 internal immutable ESTIMATED_PRIZES_PER_DRAW_FOR_10_TIERS; /// @notice The Tier liquidity data. mapping(uint8 tierId => Tier tierData) internal _tiers; /// @notice The frequency of the grand prize uint24 public immutable grandPrizePeriodDraws; /// @notice The number of shares to allocate to each prize tier. uint8 public immutable tierShares; /// @notice The number of shares to allocate to the reserve. uint8 public immutable reserveShares; /// @notice The current number of prize tokens per share. UD34x4 public prizeTokenPerShare; /// @notice The number of tiers for the last awarded draw. The last tier is the canary tier. uint8 public numberOfTiers; /// @notice The draw id of the last awarded draw. uint24 internal _lastAwardedDrawId; /// @notice The timestamp at which the last awarded draw was awarded. uint48 public lastAwardedDrawAwardedAt; /// @notice The amount of available reserve. uint96 internal _reserve; /** * @notice Constructs a new Prize Pool. * @param _numberOfTiers The number of tiers to start with. Must be greater than or equal to the minimum number of tiers. * @param _tierShares The number of shares to allocate to each tier * @param _reserveShares The number of shares to allocate to the reserve. */ constructor( uint8 _numberOfTiers, uint8 _tierShares, uint8 _reserveShares, uint24 _grandPrizePeriodDraws ) { if (_numberOfTiers < MINIMUM_NUMBER_OF_TIERS) { revert NumberOfTiersLessThanMinimum(_numberOfTiers); } if (_numberOfTiers > MAXIMUM_NUMBER_OF_TIERS) { revert NumberOfTiersGreaterThanMaximum(_numberOfTiers); } numberOfTiers = _numberOfTiers; tierShares = _tierShares; reserveShares = _reserveShares; grandPrizePeriodDraws = _grandPrizePeriodDraws; TIER_ODDS_0 = sd(1).div(sd(int24(_grandPrizePeriodDraws))); TIER_ODDS_EVERY_DRAW = SD59x18.wrap(1000000000000000000); TIER_ODDS_1_4 = TierCalculationLib.getTierOdds(1, 3, _grandPrizePeriodDraws); TIER_ODDS_1_5 = TierCalculationLib.getTierOdds(1, 4, _grandPrizePeriodDraws); TIER_ODDS_2_5 = TierCalculationLib.getTierOdds(2, 4, _grandPrizePeriodDraws); TIER_ODDS_1_6 = TierCalculationLib.getTierOdds(1, 5, _grandPrizePeriodDraws); TIER_ODDS_2_6 = TierCalculationLib.getTierOdds(2, 5, _grandPrizePeriodDraws); TIER_ODDS_3_6 = TierCalculationLib.getTierOdds(3, 5, _grandPrizePeriodDraws); TIER_ODDS_1_7 = TierCalculationLib.getTierOdds(1, 6, _grandPrizePeriodDraws); TIER_ODDS_2_7 = TierCalculationLib.getTierOdds(2, 6, _grandPrizePeriodDraws); TIER_ODDS_3_7 = TierCalculationLib.getTierOdds(3, 6, _grandPrizePeriodDraws); TIER_ODDS_4_7 = TierCalculationLib.getTierOdds(4, 6, _grandPrizePeriodDraws); TIER_ODDS_1_8 = TierCalculationLib.getTierOdds(1, 7, _grandPrizePeriodDraws); TIER_ODDS_2_8 = TierCalculationLib.getTierOdds(2, 7, _grandPrizePeriodDraws); TIER_ODDS_3_8 = TierCalculationLib.getTierOdds(3, 7, _grandPrizePeriodDraws); TIER_ODDS_4_8 = TierCalculationLib.getTierOdds(4, 7, _grandPrizePeriodDraws); TIER_ODDS_5_8 = TierCalculationLib.getTierOdds(5, 7, _grandPrizePeriodDraws); TIER_ODDS_1_9 = TierCalculationLib.getTierOdds(1, 8, _grandPrizePeriodDraws); TIER_ODDS_2_9 = TierCalculationLib.getTierOdds(2, 8, _grandPrizePeriodDraws); TIER_ODDS_3_9 = TierCalculationLib.getTierOdds(3, 8, _grandPrizePeriodDraws); TIER_ODDS_4_9 = TierCalculationLib.getTierOdds(4, 8, _grandPrizePeriodDraws); TIER_ODDS_5_9 = TierCalculationLib.getTierOdds(5, 8, _grandPrizePeriodDraws); TIER_ODDS_6_9 = TierCalculationLib.getTierOdds(6, 8, _grandPrizePeriodDraws); TIER_ODDS_1_10 = TierCalculationLib.getTierOdds(1, 9, _grandPrizePeriodDraws); TIER_ODDS_2_10 = TierCalculationLib.getTierOdds(2, 9, _grandPrizePeriodDraws); TIER_ODDS_3_10 = TierCalculationLib.getTierOdds(3, 9, _grandPrizePeriodDraws); TIER_ODDS_4_10 = TierCalculationLib.getTierOdds(4, 9, _grandPrizePeriodDraws); TIER_ODDS_5_10 = TierCalculationLib.getTierOdds(5, 9, _grandPrizePeriodDraws); TIER_ODDS_6_10 = TierCalculationLib.getTierOdds(6, 9, _grandPrizePeriodDraws); TIER_ODDS_7_10 = TierCalculationLib.getTierOdds(7, 9, _grandPrizePeriodDraws); ESTIMATED_PRIZES_PER_DRAW_FOR_3_TIERS = _sumTierPrizeCounts(3); ESTIMATED_PRIZES_PER_DRAW_FOR_4_TIERS = _sumTierPrizeCounts(4); ESTIMATED_PRIZES_PER_DRAW_FOR_5_TIERS = _sumTierPrizeCounts(5); ESTIMATED_PRIZES_PER_DRAW_FOR_6_TIERS = _sumTierPrizeCounts(6); ESTIMATED_PRIZES_PER_DRAW_FOR_7_TIERS = _sumTierPrizeCounts(7); ESTIMATED_PRIZES_PER_DRAW_FOR_8_TIERS = _sumTierPrizeCounts(8); ESTIMATED_PRIZES_PER_DRAW_FOR_9_TIERS = _sumTierPrizeCounts(9); ESTIMATED_PRIZES_PER_DRAW_FOR_10_TIERS = _sumTierPrizeCounts(10); } /// @notice Adjusts the number of tiers and distributes new liquidity. /// @param _awardingDraw The ID of the draw that is being awarded /// @param _nextNumberOfTiers The new number of tiers. Must be greater than minimum /// @param _prizeTokenLiquidity The amount of fresh liquidity to distribute across the tiers and reserve function _awardDraw( uint24 _awardingDraw, uint8 _nextNumberOfTiers, uint256 _prizeTokenLiquidity ) internal { if (_nextNumberOfTiers < MINIMUM_NUMBER_OF_TIERS) { revert NumberOfTiersLessThanMinimum(_nextNumberOfTiers); } uint8 numTiers = numberOfTiers; UD34x4 _prizeTokenPerShare = prizeTokenPerShare; UD60x18 _prizeTokenPerShareUD60x18 = fromUD34x4toUD60x18(_prizeTokenPerShare); (uint96 newReserve, UD60x18 newPrizeTokenPerShare) = _computeNewDistributions( numTiers, _nextNumberOfTiers, _prizeTokenPerShareUD60x18, _prizeTokenLiquidity ); // need to redistribute to the canary tier and any new tiers (if expanding) uint8 start; uint8 end; // if we are expanding, need to reset the canary tier and all of the new tiers if (_nextNumberOfTiers > numTiers) { start = numTiers - 1; end = _nextNumberOfTiers; } else { // just reset the canary tier start = _nextNumberOfTiers - 1; end = _nextNumberOfTiers; } for (uint8 i = start; i < end; i++) { _tiers[i] = Tier({ drawId: _awardingDraw, prizeTokenPerShare: _prizeTokenPerShare, prizeSize: _computePrizeSize( i, _nextNumberOfTiers, _prizeTokenPerShareUD60x18, newPrizeTokenPerShare ) }); } prizeTokenPerShare = fromUD60x18toUD34x4(newPrizeTokenPerShare); numberOfTiers = _nextNumberOfTiers; _lastAwardedDrawId = _awardingDraw; lastAwardedDrawAwardedAt = uint48(block.timestamp); _reserve += newReserve; } /// @notice Computes the liquidity that will be distributed for the next awarded draw given the next number of tiers and prize liquidity. /// @param _numberOfTiers The current number of tiers /// @param _nextNumberOfTiers The next number of tiers to use to compute distribution /// @param _currentPrizeTokenPerShare The current prize token per share /// @param _prizeTokenLiquidity The amount of fresh liquidity to distribute across the tiers and reserve /// @return newReserve The amount of liquidity that will be added to the reserve /// @return newPrizeTokenPerShare The new prize token per share function _computeNewDistributions( uint8 _numberOfTiers, uint8 _nextNumberOfTiers, UD60x18 _currentPrizeTokenPerShare, uint256 _prizeTokenLiquidity ) internal view returns (uint96 newReserve, UD60x18 newPrizeTokenPerShare) { UD60x18 reclaimedLiquidity; { // need to redistribute to the canary tier and any new tiers (if expanding) uint8 start; uint8 end; uint8 shares = tierShares; // if we are shrinking, we need to reclaim including the new canary tier if (_nextNumberOfTiers < _numberOfTiers) { start = _nextNumberOfTiers - 1; end = _numberOfTiers; } else { // just reset the canary tier start = _numberOfTiers - 1; end = _numberOfTiers; } for (uint8 i = start; i < end; i++) { reclaimedLiquidity = reclaimedLiquidity.add( _getTierRemainingLiquidity( shares, fromUD34x4toUD60x18(_tiers[i].prizeTokenPerShare), _currentPrizeTokenPerShare ) ); } } uint256 totalNewLiquidity = _prizeTokenLiquidity + convert(reclaimedLiquidity); uint256 nextTotalShares = _getTotalShares(_nextNumberOfTiers); uint256 deltaPrizeTokensPerShare = totalNewLiquidity / nextTotalShares; newPrizeTokenPerShare = _currentPrizeTokenPerShare.add(convert(deltaPrizeTokensPerShare)); newReserve = SafeCast.toUint96( // reserve portion of new liquidity deltaPrizeTokensPerShare * reserveShares + // remainder left over from shares totalNewLiquidity - deltaPrizeTokensPerShare * nextTotalShares ); } /// @notice Returns the prize size for the given tier. /// @param _tier The tier to retrieve /// @return The prize size for the tier function getTierPrizeSize(uint8 _tier) external view returns (uint104) { uint8 _numTiers = numberOfTiers; return !TierCalculationLib.isValidTier(_tier, _numTiers) ? 0 : _getTier(_tier, _numTiers).prizeSize; } /// @notice Returns the estimated number of prizes for the given tier. /// @param _tier The tier to retrieve /// @return The estimated number of prizes function getTierPrizeCount(uint8 _tier) external view returns (uint32) { return !TierCalculationLib.isValidTier(_tier, numberOfTiers) ? 0 : uint32(TierCalculationLib.prizeCount(_tier)); } /// @notice Retrieves an up-to-date Tier struct for the given tier. /// @param _tier The tier to retrieve /// @param _numberOfTiers The number of tiers, should match the current. Passed explicitly as an optimization /// @return An up-to-date Tier struct; if the prize is outdated then it is recomputed based on available liquidity and the draw ID is updated. function _getTier(uint8 _tier, uint8 _numberOfTiers) internal view returns (Tier memory) { Tier memory tier = _tiers[_tier]; uint24 lastAwardedDrawId_ = _lastAwardedDrawId; if (tier.drawId != lastAwardedDrawId_) { tier.drawId = lastAwardedDrawId_; tier.prizeSize = _computePrizeSize( _tier, _numberOfTiers, fromUD34x4toUD60x18(tier.prizeTokenPerShare), fromUD34x4toUD60x18(prizeTokenPerShare) ); } return tier; } /// @notice Computes the total shares in the system. That is `(number of tiers * tier shares) + reserve shares`. /// @return The total shares function getTotalShares() external view returns (uint256) { return _getTotalShares(numberOfTiers); } /// @notice Computes the total shares in the system given the number of tiers. That is `(number of tiers * tier shares) + reserve shares`. /// @param _numberOfTiers The number of tiers to calculate the total shares for /// @return The total shares function _getTotalShares(uint8 _numberOfTiers) internal view returns (uint256) { return uint256(_numberOfTiers) * uint256(tierShares) + uint256(reserveShares); } /// @notice Consumes liquidity from the given tier. /// @param _tierStruct The tier to consume liquidity from /// @param _tier The tier number /// @param _liquidity The amount of liquidity to consume function _consumeLiquidity(Tier memory _tierStruct, uint8 _tier, uint104 _liquidity) internal { uint8 _shares = tierShares; uint104 remainingLiquidity = SafeCast.toUint104( convert( _getTierRemainingLiquidity( _shares, fromUD34x4toUD60x18(_tierStruct.prizeTokenPerShare), fromUD34x4toUD60x18(prizeTokenPerShare) ) ) ); if (_liquidity > remainingLiquidity) { uint96 excess = SafeCast.toUint96(_liquidity - remainingLiquidity); if (excess > _reserve) { revert InsufficientLiquidity(_liquidity); } unchecked { _reserve -= excess; } emit ReserveConsumed(excess); _tierStruct.prizeTokenPerShare = prizeTokenPerShare; } else { _tierStruct.prizeTokenPerShare = UD34x4.wrap( UD34x4.unwrap(_tierStruct.prizeTokenPerShare) + UD34x4.unwrap(fromUD60x18toUD34x4(convert(_liquidity).div(convert(_shares)))) ); } _tiers[_tier] = _tierStruct; } /// @notice Computes the prize size of the given tier. /// @param _tier The tier to compute the prize size of /// @param _numberOfTiers The current number of tiers /// @param _tierPrizeTokenPerShare The prizeTokenPerShare of the Tier struct /// @param _prizeTokenPerShare The global prizeTokenPerShare /// @return The prize size function _computePrizeSize( uint8 _tier, uint8 _numberOfTiers, UD60x18 _tierPrizeTokenPerShare, UD60x18 _prizeTokenPerShare ) internal view returns (uint104) { uint256 prizeSize; if (_prizeTokenPerShare.gt(_tierPrizeTokenPerShare)) { prizeSize = _computePrizeSize( _tierPrizeTokenPerShare, _prizeTokenPerShare, convert(TierCalculationLib.prizeCount(_tier)), tierShares ); bool canExpand = _numberOfTiers < MAXIMUM_NUMBER_OF_TIERS; if (canExpand && _isCanaryTier(_tier, _numberOfTiers)) { // make canary prizes smaller to account for reduction in shares for next number of tiers prizeSize = (prizeSize * _getTotalShares(_numberOfTiers)) / _getTotalShares(_numberOfTiers + 1); } } return prizeSize > type(uint104).max ? type(uint104).max : uint104(prizeSize); } /// @notice Computes the prize size with the given parameters. /// @param _tierPrizeTokenPerShare The prizeTokenPerShare of the Tier struct /// @param _prizeTokenPerShare The global prizeTokenPerShare /// @param _fractionalPrizeCount The prize count as UD60x18 /// @param _shares The number of shares that the tier has /// @return The prize size function _computePrizeSize( UD60x18 _tierPrizeTokenPerShare, UD60x18 _prizeTokenPerShare, UD60x18 _fractionalPrizeCount, uint8 _shares ) internal pure returns (uint256) { return convert( _prizeTokenPerShare.sub(_tierPrizeTokenPerShare).mul(convert(_shares)).div( _fractionalPrizeCount ) ); } /// @notice Determines if the given tier is the canary tier. /// @param _tier The tier to check /// @param _numberOfTiers The current number of tiers /// @return True if the tier is the canary tier function _isCanaryTier(uint8 _tier, uint8 _numberOfTiers) internal pure returns (bool) { return _tier == _numberOfTiers - 1; } /// @notice Computes the remaining liquidity available to a tier. /// @param _tier The tier to compute the liquidity for /// @return The remaining liquidity function getTierRemainingLiquidity(uint8 _tier) external view returns (uint256) { uint8 _numTiers = numberOfTiers; return !TierCalculationLib.isValidTier(_tier, _numTiers) ? 0 : convert( _getTierRemainingLiquidity( tierShares, fromUD34x4toUD60x18(_getTier(_tier, _numTiers).prizeTokenPerShare), fromUD34x4toUD60x18(prizeTokenPerShare) ) ); } /// @notice Computes the remaining tier liquidity. /// @param _shares The number of shares that the tier has (can be tierShares or canaryShares) /// @param _tierPrizeTokenPerShare The prizeTokenPerShare of the Tier struct /// @param _prizeTokenPerShare The global prizeTokenPerShare /// @return The remaining available liquidity function _getTierRemainingLiquidity( uint256 _shares, UD60x18 _tierPrizeTokenPerShare, UD60x18 _prizeTokenPerShare ) internal pure returns (UD60x18) { return _tierPrizeTokenPerShare.gte(_prizeTokenPerShare) ? ud(0) : _prizeTokenPerShare.sub(_tierPrizeTokenPerShare).mul(convert(_shares)); } /// @notice Estimates the number of prizes for the current number of tiers, including the canary tier /// @return The estimated number of prizes including the canary tier function estimatedPrizeCount() external view returns (uint32) { return _estimatePrizeCountPerDrawUsingNumberOfTiers(numberOfTiers); } /// @notice Estimates the number of prizes that will be awarded given a number of tiers. Includes canary tier /// @param numTiers The number of tiers /// @return The estimated prize count for the given number of tiers function estimatedPrizeCount(uint8 numTiers) external view returns (uint32) { return _estimatePrizeCountPerDrawUsingNumberOfTiers(numTiers); } /// @notice Returns the balance of the reserve. /// @return The amount of tokens that have been reserved. function reserve() external view returns (uint96) { return _reserve; } /// @notice Estimates the prize count for the given tier. /// @param numTiers The number of prize tiers /// @return The estimated total number of prizes function _estimatePrizeCountPerDrawUsingNumberOfTiers( uint8 numTiers ) internal view returns (uint32) { if (numTiers == 3) { return ESTIMATED_PRIZES_PER_DRAW_FOR_3_TIERS; } else if (numTiers == 4) { return ESTIMATED_PRIZES_PER_DRAW_FOR_4_TIERS; } else if (numTiers == 5) { return ESTIMATED_PRIZES_PER_DRAW_FOR_5_TIERS; } else if (numTiers == 6) { return ESTIMATED_PRIZES_PER_DRAW_FOR_6_TIERS; } else if (numTiers == 7) { return ESTIMATED_PRIZES_PER_DRAW_FOR_7_TIERS; } else if (numTiers == 8) { return ESTIMATED_PRIZES_PER_DRAW_FOR_8_TIERS; } else if (numTiers == 9) { return ESTIMATED_PRIZES_PER_DRAW_FOR_9_TIERS; } else if (numTiers == 10) { return ESTIMATED_PRIZES_PER_DRAW_FOR_10_TIERS; } return 0; } /// @notice Estimates the number of tiers for the given prize count. /// @dev Can return lower than the minimum, so that minimum can be detected /// @param _prizeCount The number of prizes that were claimed /// @return The estimated tier function _estimateNumberOfTiersUsingPrizeCountPerDraw( uint32 _prizeCount ) internal view returns (uint8) { // the prize count is slightly more than 4x for each higher tier. i.e. 16, 66, 270, 1108, etc // by doubling the measured count, we create a safe margin for error. uint32 _adjustedPrizeCount = _prizeCount * 2; if (_adjustedPrizeCount < ESTIMATED_PRIZES_PER_DRAW_FOR_3_TIERS) { return 2; // include 2 so we can detect minimum } else if (_adjustedPrizeCount < ESTIMATED_PRIZES_PER_DRAW_FOR_4_TIERS) { return 3; } else if (_adjustedPrizeCount < ESTIMATED_PRIZES_PER_DRAW_FOR_5_TIERS) { return 4; } else if (_adjustedPrizeCount < ESTIMATED_PRIZES_PER_DRAW_FOR_6_TIERS) { return 5; } else if (_adjustedPrizeCount < ESTIMATED_PRIZES_PER_DRAW_FOR_7_TIERS) { return 6; } else if (_adjustedPrizeCount < ESTIMATED_PRIZES_PER_DRAW_FOR_8_TIERS) { return 7; } else if (_adjustedPrizeCount < ESTIMATED_PRIZES_PER_DRAW_FOR_9_TIERS) { return 8; } else if (_adjustedPrizeCount < ESTIMATED_PRIZES_PER_DRAW_FOR_10_TIERS) { return 9; } return 10; } /// @notice Computes the odds for a tier given the number of tiers. /// @param _tier The tier to compute odds for /// @param _numTiers The number of prize tiers /// @return The odds of the tier function getTierOdds(uint8 _tier, uint8 _numTiers) external view returns (SD59x18) { return _tierOdds(_tier, _numTiers); } /// @notice Computes the expected number of prizes for a given number of tiers. /// @dev Includes the canary tier /// @param _numTiers The number of tiers /// @return The expected number of prizes, canary included. function _sumTierPrizeCounts(uint8 _numTiers) internal view returns (uint32) { uint32 prizeCount; uint8 i = 0; do { prizeCount += TierCalculationLib.tierPrizeCountPerDraw(i, _tierOdds(i, _numTiers)); i++; } while (i < _numTiers); return prizeCount; } /// @notice Computes the odds for a tier given the number of tiers. /// @param _tier The tier to compute odds for /// @param _numTiers The number of prize tiers /// @return The odds of the tier function _tierOdds(uint8 _tier, uint8 _numTiers) internal view returns (SD59x18) { if (_tier == 0) return TIER_ODDS_0; if (_numTiers == 3) { if (_tier <= 2) return TIER_ODDS_EVERY_DRAW; } else if (_numTiers == 4) { if (_tier == 1) return TIER_ODDS_1_4; else if (_tier <= 3) return TIER_ODDS_EVERY_DRAW; } else if (_numTiers == 5) { if (_tier == 1) return TIER_ODDS_1_5; else if (_tier == 2) return TIER_ODDS_2_5; else if (_tier <= 4) return TIER_ODDS_EVERY_DRAW; } else if (_numTiers == 6) { if (_tier == 1) return TIER_ODDS_1_6; else if (_tier == 2) return TIER_ODDS_2_6; else if (_tier == 3) return TIER_ODDS_3_6; else if (_tier <= 5) return TIER_ODDS_EVERY_DRAW; } else if (_numTiers == 7) { if (_tier == 1) return TIER_ODDS_1_7; else if (_tier == 2) return TIER_ODDS_2_7; else if (_tier == 3) return TIER_ODDS_3_7; else if (_tier == 4) return TIER_ODDS_4_7; else if (_tier <= 6) return TIER_ODDS_EVERY_DRAW; } else if (_numTiers == 8) { if (_tier == 1) return TIER_ODDS_1_8; else if (_tier == 2) return TIER_ODDS_2_8; else if (_tier == 3) return TIER_ODDS_3_8; else if (_tier == 4) return TIER_ODDS_4_8; else if (_tier == 5) return TIER_ODDS_5_8; else if (_tier <= 7) return TIER_ODDS_EVERY_DRAW; } else if (_numTiers == 9) { if (_tier == 1) return TIER_ODDS_1_9; else if (_tier == 2) return TIER_ODDS_2_9; else if (_tier == 3) return TIER_ODDS_3_9; else if (_tier == 4) return TIER_ODDS_4_9; else if (_tier == 5) return TIER_ODDS_5_9; else if (_tier == 6) return TIER_ODDS_6_9; else if (_tier <= 8) return TIER_ODDS_EVERY_DRAW; } else if (_numTiers == 10) { if (_tier == 1) return TIER_ODDS_1_10; else if (_tier == 2) return TIER_ODDS_2_10; else if (_tier == 3) return TIER_ODDS_3_10; else if (_tier == 4) return TIER_ODDS_4_10; else if (_tier == 5) return TIER_ODDS_5_10; else if (_tier == 6) return TIER_ODDS_6_10; else if (_tier == 7) return TIER_ODDS_7_10; else if (_tier <= 9) return TIER_ODDS_EVERY_DRAW; } return sd(0); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { UniformRandomNumber } from "uniform-random-number/UniformRandomNumber.sol"; import { SD59x18, sd, unwrap, convert } from "prb-math/SD59x18.sol"; /// @title Tier Calculation Library /// @author PoolTogether Inc. Team /// @notice Provides helper functions to assist in calculating tier prize counts, frequency, and odds. library TierCalculationLib { /// @notice Calculates the odds of a tier occurring. /// @param _tier The tier to calculate odds for /// @param _numberOfTiers The total number of tiers /// @param _grandPrizePeriod The number of draws between grand prizes /// @return The odds that a tier should occur for a single draw. function getTierOdds( uint8 _tier, uint8 _numberOfTiers, uint24 _grandPrizePeriod ) internal pure returns (SD59x18) { int8 oneMinusNumTiers = 1 - int8(_numberOfTiers); return sd(1).div(sd(int24(_grandPrizePeriod))).pow( sd(int8(_tier) + oneMinusNumTiers).div(sd(oneMinusNumTiers)) ); } /// @notice Estimates the number of draws between a tier occurring. /// @param _tierOdds The odds for the tier to calculate the frequency of /// @return The estimated number of draws between the tier occurring function estimatePrizeFrequencyInDraws(SD59x18 _tierOdds) internal pure returns (uint256) { return uint256(convert(sd(1e18).div(_tierOdds).ceil())); } /// @notice Computes the number of prizes for a given tier. /// @param _tier The tier to compute for /// @return The number of prizes function prizeCount(uint8 _tier) internal pure returns (uint256) { return 4 ** _tier; } /// @notice Determines if a user won a prize tier. /// @param _userSpecificRandomNumber The random number to use as entropy /// @param _userTwab The user's time weighted average balance /// @param _vaultTwabTotalSupply The vault's time weighted average total supply /// @param _vaultContributionFraction The portion of the prize that was contributed by the vault /// @param _tierOdds The odds of the tier occurring /// @return True if the user won the tier, false otherwise function isWinner( uint256 _userSpecificRandomNumber, uint256 _userTwab, uint256 _vaultTwabTotalSupply, SD59x18 _vaultContributionFraction, SD59x18 _tierOdds ) internal pure returns (bool) { if (_vaultTwabTotalSupply == 0) { return false; } /* The user-held portion of the total supply is the "winning zone". If the above pseudo-random number falls within the winning zone, the user has won this tier. However, we scale the size of the zone based on: - Odds of the tier occurring - Number of prizes - Portion of prize that was contributed by the vault */ return UniformRandomNumber.uniform(_userSpecificRandomNumber, _vaultTwabTotalSupply) < calculateWinningZone(_userTwab, _vaultContributionFraction, _tierOdds); } /// @notice Calculates a pseudo-random number that is unique to the user, tier, and winning random number. /// @param _drawId The draw id the user is checking /// @param _vault The vault the user deposited into /// @param _user The user /// @param _tier The tier /// @param _prizeIndex The particular prize index they are checking /// @param _winningRandomNumber The winning random number /// @return A pseudo-random number function calculatePseudoRandomNumber( uint24 _drawId, address _vault, address _user, uint8 _tier, uint32 _prizeIndex, uint256 _winningRandomNumber ) internal pure returns (uint256) { return uint256( keccak256(abi.encode(_drawId, _vault, _user, _tier, _prizeIndex, _winningRandomNumber)) ); } /// @notice Calculates the winning zone for a user. If their pseudo-random number falls within this zone, they win the tier. /// @param _userTwab The user's time weighted average balance /// @param _vaultContributionFraction The portion of the prize that was contributed by the vault /// @param _tierOdds The odds of the tier occurring /// @return The winning zone for the user. function calculateWinningZone( uint256 _userTwab, SD59x18 _vaultContributionFraction, SD59x18 _tierOdds ) internal pure returns (uint256) { return uint256(convert(convert(int256(_userTwab)).mul(_tierOdds).mul(_vaultContributionFraction))); } /// @notice Computes the estimated number of prizes per draw for a given tier and tier odds. /// @param _tier The tier /// @param _odds The odds of the tier occurring for the draw /// @return The estimated number of prizes per draw for the given tier and tier odds function tierPrizeCountPerDraw(uint8 _tier, SD59x18 _odds) internal pure returns (uint32) { return uint32(uint256(unwrap(sd(int256(prizeCount(_tier))).mul(_odds)))); } /// @notice Checks whether a tier is a valid tier /// @param _tier The tier to check /// @param _numberOfTiers The number of tiers /// @return True if the tier is valid, false otherwise function isValidTier(uint8 _tier, uint8 _numberOfTiers) internal pure returns (bool) { return _tier < _numberOfTiers; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "ring-buffer-lib/RingBufferLib.sol"; import { ObservationLib, MAX_CARDINALITY } from "./ObservationLib.sol"; type PeriodOffsetRelativeTimestamp is uint32; /// @notice Emitted when a balance is decreased by an amount that exceeds the amount available. /// @param balance The current balance of the account /// @param amount The amount being decreased from the account's balance /// @param message An additional message describing the error error BalanceLTAmount(uint96 balance, uint96 amount, string message); /// @notice Emitted when a delegate balance is decreased by an amount that exceeds the amount available. /// @param delegateBalance The current delegate balance of the account /// @param delegateAmount The amount being decreased from the account's delegate balance /// @param message An additional message describing the error error DelegateBalanceLTAmount(uint96 delegateBalance, uint96 delegateAmount, string message); /// @notice Emitted when a request is made for a twab that is not yet finalized. /// @param timestamp The requested timestamp /// @param currentOverwritePeriodStartedAt The current overwrite period start time error TimestampNotFinalized(uint256 timestamp, uint256 currentOverwritePeriodStartedAt); /// @notice Emitted when a TWAB time range start is after the end. /// @param start The start time /// @param end The end time error InvalidTimeRange(uint256 start, uint256 end); /// @notice Emitted when there is insufficient history to lookup a twab time range /// @param requestedTimestamp The timestamp requested /// @param oldestTimestamp The oldest timestamp that can be read error InsufficientHistory( PeriodOffsetRelativeTimestamp requestedTimestamp, PeriodOffsetRelativeTimestamp oldestTimestamp ); /** * @title PoolTogether V5 TwabLib (Library) * @author PoolTogether Inc. & G9 Software Inc. * @dev Time-Weighted Average Balance Library for ERC20 tokens. * @notice This TwabLib adds on-chain historical lookups to a user(s) time-weighted average balance. * Each user is mapped to an Account struct containing the TWAB history (ring buffer) and * ring buffer parameters. Every token.transfer() creates a new TWAB checkpoint. The new * TWAB checkpoint is stored in the circular ring buffer, as either a new checkpoint or * rewriting a previous checkpoint with new parameters. One checkpoint per day is stored. * The TwabLib guarantees minimum 1 year of search history. * @notice There are limitations to the Observation data structure used. Ensure your token is * compatible before using this library. Ensure the date ranges you're relying on are * within safe boundaries. */ library TwabLib { /** * @notice Struct ring buffer parameters for single user Account. * @param balance Current token balance for an Account * @param delegateBalance Current delegate balance for an Account (active balance for chance) * @param nextObservationIndex Next uninitialized or updatable ring buffer checkpoint storage slot * @param cardinality Current total "initialized" ring buffer checkpoints for single user Account. * Used to set initial boundary conditions for an efficient binary search. */ struct AccountDetails { uint96 balance; uint96 delegateBalance; uint16 nextObservationIndex; uint16 cardinality; } /** * @notice Account details and historical twabs. * @dev The size of observations is MAX_CARDINALITY from the ObservationLib. * @param details The account details * @param observations The history of observations for this account */ struct Account { AccountDetails details; ObservationLib.Observation[17520] observations; } /** * @notice Increase a user's balance and delegate balance by a given amount. * @dev This function mutates the provided account. * @param PERIOD_LENGTH The length of an overwrite period * @param PERIOD_OFFSET The offset of the first period * @param _account The account to update * @param _amount The amount to increase the balance by * @param _delegateAmount The amount to increase the delegate balance by * @return observation The new/updated observation * @return isNew Whether or not the observation is new or overwrote a previous one * @return isObservationRecorded Whether or not an observation was recorded to storage */ function increaseBalances( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, Account storage _account, uint96 _amount, uint96 _delegateAmount ) internal returns ( ObservationLib.Observation memory observation, bool isNew, bool isObservationRecorded, AccountDetails memory accountDetails ) { accountDetails = _account.details; // record a new observation if the delegateAmount is non-zero and time has not overflowed. isObservationRecorded = _delegateAmount != uint96(0) && (block.timestamp - PERIOD_OFFSET) <= type(uint32).max; accountDetails.balance += _amount; accountDetails.delegateBalance += _delegateAmount; // Only record a new Observation if the users delegateBalance has changed. if (isObservationRecorded) { (observation, isNew, accountDetails) = _recordObservation( PERIOD_LENGTH, PERIOD_OFFSET, accountDetails, _account ); } _account.details = accountDetails; } /** * @notice Decrease a user's balance and delegate balance by a given amount. * @dev This function mutates the provided account. * @param PERIOD_LENGTH The length of an overwrite period * @param PERIOD_OFFSET The offset of the first period * @param _account The account to update * @param _amount The amount to decrease the balance by * @param _delegateAmount The amount to decrease the delegate balance by * @param _revertMessage The revert message to use if the balance is insufficient * @return observation The new/updated observation * @return isNew Whether or not the observation is new or overwrote a previous one * @return isObservationRecorded Whether or not the observation was recorded to storage */ function decreaseBalances( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, Account storage _account, uint96 _amount, uint96 _delegateAmount, string memory _revertMessage ) internal returns ( ObservationLib.Observation memory observation, bool isNew, bool isObservationRecorded, AccountDetails memory accountDetails ) { accountDetails = _account.details; if (accountDetails.balance < _amount) { revert BalanceLTAmount(accountDetails.balance, _amount, _revertMessage); } if (accountDetails.delegateBalance < _delegateAmount) { revert DelegateBalanceLTAmount( accountDetails.delegateBalance, _delegateAmount, _revertMessage ); } // record a new observation if the delegateAmount is non-zero and time has not overflowed. isObservationRecorded = _delegateAmount != uint96(0) && (block.timestamp - PERIOD_OFFSET) <= type(uint32).max; unchecked { accountDetails.balance -= _amount; accountDetails.delegateBalance -= _delegateAmount; } // Only record a new Observation if the users delegateBalance has changed. if (isObservationRecorded) { (observation, isNew, accountDetails) = _recordObservation( PERIOD_LENGTH, PERIOD_OFFSET, accountDetails, _account ); } _account.details = accountDetails; } /** * @notice Looks up the oldest observation in the circular buffer. * @param _observations The circular buffer of observations * @param _accountDetails The account details to query with * @return index The index of the oldest observation * @return observation The oldest observation in the circular buffer */ function getOldestObservation( ObservationLib.Observation[MAX_CARDINALITY] storage _observations, AccountDetails memory _accountDetails ) internal view returns (uint16 index, ObservationLib.Observation memory observation) { // If the circular buffer has not been fully populated, we go to the beginning of the buffer at index 0. if (_accountDetails.cardinality < MAX_CARDINALITY) { index = 0; observation = _observations[0]; } else { index = _accountDetails.nextObservationIndex; observation = _observations[index]; } } /** * @notice Looks up the newest observation in the circular buffer. * @param _observations The circular buffer of observations * @param _accountDetails The account details to query with * @return index The index of the newest observation * @return observation The newest observation in the circular buffer */ function getNewestObservation( ObservationLib.Observation[MAX_CARDINALITY] storage _observations, AccountDetails memory _accountDetails ) internal view returns (uint16 index, ObservationLib.Observation memory observation) { index = uint16( RingBufferLib.newestIndex(_accountDetails.nextObservationIndex, MAX_CARDINALITY) ); observation = _observations[index]; } /** * @notice Looks up a users balance at a specific time in the past. The time must be before the current overwrite period. * @dev Ensure timestamps are safe using requireFinalized * @param PERIOD_LENGTH The length of an overwrite period * @param PERIOD_OFFSET The offset of the first period * @param _observations The circular buffer of observations * @param _accountDetails The account details to query with * @param _targetTime The time to look up the balance at * @return balance The balance at the target time */ function getBalanceAt( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, ObservationLib.Observation[MAX_CARDINALITY] storage _observations, AccountDetails memory _accountDetails, uint256 _targetTime ) internal view requireFinalized(PERIOD_LENGTH, PERIOD_OFFSET, _targetTime) returns (uint256) { if (_targetTime < PERIOD_OFFSET) { return 0; } uint256 offsetTargetTime = _targetTime - PERIOD_OFFSET; // if this is for an overflowed time period, return 0 if (offsetTargetTime > type(uint32).max) { return 0; } ObservationLib.Observation memory prevOrAtObservation = _getPreviousOrAtObservation( _observations, _accountDetails, PeriodOffsetRelativeTimestamp.wrap(uint32(offsetTargetTime)) ); return prevOrAtObservation.balance; } /** * @notice Looks up a users TWAB for a time range. The time must be before the current overwrite period. * @dev If the timestamps in the range are not exact matches of observations, the balance is extrapolated using the previous observation. * @param PERIOD_LENGTH The length of an overwrite period * @param PERIOD_OFFSET The offset of the first period * @param _observations The circular buffer of observations * @param _accountDetails The account details to query with * @param _startTime The start of the time range * @param _endTime The end of the time range * @return twab The TWAB for the time range */ function getTwabBetween( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, ObservationLib.Observation[MAX_CARDINALITY] storage _observations, AccountDetails memory _accountDetails, uint256 _startTime, uint256 _endTime ) internal view requireFinalized(PERIOD_LENGTH, PERIOD_OFFSET, _endTime) returns (uint256) { if (_endTime < _startTime) { revert InvalidTimeRange(_startTime, _endTime); } uint256 offsetStartTime = _startTime - PERIOD_OFFSET; uint256 offsetEndTime = _endTime - PERIOD_OFFSET; // if the either time has overflowed, then return 0. if (offsetStartTime > type(uint32).max || offsetEndTime > type(uint32).max) { return 0; } ObservationLib.Observation memory endObservation = _getPreviousOrAtObservation( _observations, _accountDetails, PeriodOffsetRelativeTimestamp.wrap(uint32(offsetEndTime)) ); if (offsetStartTime == offsetEndTime) { return endObservation.balance; } ObservationLib.Observation memory startObservation = _getPreviousOrAtObservation( _observations, _accountDetails, PeriodOffsetRelativeTimestamp.wrap(uint32(offsetStartTime)) ); if (startObservation.timestamp != offsetStartTime) { startObservation = _calculateTemporaryObservation( startObservation, PeriodOffsetRelativeTimestamp.wrap(uint32(offsetStartTime)) ); } if (endObservation.timestamp != offsetEndTime) { endObservation = _calculateTemporaryObservation( endObservation, PeriodOffsetRelativeTimestamp.wrap(uint32(offsetEndTime)) ); } // Difference in amount / time return (endObservation.cumulativeBalance - startObservation.cumulativeBalance) / (offsetEndTime - offsetStartTime); } /** * @notice Given an AccountDetails with updated balances, either updates the latest Observation or records a new one * @param PERIOD_LENGTH The overwrite period length * @param PERIOD_OFFSET The overwrite period offset * @param _accountDetails The updated account details * @param _account The account to update * @return observation The new/updated observation * @return isNew Whether or not the observation is new or overwrote a previous one * @return newAccountDetails The new account details */ function _recordObservation( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, AccountDetails memory _accountDetails, Account storage _account ) internal returns ( ObservationLib.Observation memory observation, bool isNew, AccountDetails memory newAccountDetails ) { PeriodOffsetRelativeTimestamp currentTime = PeriodOffsetRelativeTimestamp.wrap( uint32(block.timestamp - PERIOD_OFFSET) ); uint16 nextIndex; ObservationLib.Observation memory newestObservation; (nextIndex, newestObservation, isNew) = _getNextObservationIndex( PERIOD_LENGTH, PERIOD_OFFSET, _account.observations, _accountDetails ); if (isNew) { // If the index is new, then we increase the next index to use _accountDetails.nextObservationIndex = uint16( RingBufferLib.nextIndex(uint256(nextIndex), MAX_CARDINALITY) ); // Prevent the Account specific cardinality from exceeding the MAX_CARDINALITY. // The ring buffer length is limited by MAX_CARDINALITY. IF the account.cardinality // exceeds the max cardinality, new observations would be incorrectly set or the // observation would be out of "bounds" of the ring buffer. Once reached the // Account.cardinality will continue to be equal to max cardinality. _accountDetails.cardinality = _accountDetails.cardinality < MAX_CARDINALITY ? _accountDetails.cardinality + 1 : MAX_CARDINALITY; } observation = ObservationLib.Observation({ cumulativeBalance: _extrapolateFromBalance(newestObservation, currentTime), balance: _accountDetails.delegateBalance, timestamp: PeriodOffsetRelativeTimestamp.unwrap(currentTime) }); // Write to storage _account.observations[nextIndex] = observation; newAccountDetails = _accountDetails; } /** * @notice Calculates a temporary observation for a given time using the previous observation. * @dev This is used to extrapolate a balance for any given time. * @param _observation The previous observation * @param _time The time to extrapolate to */ function _calculateTemporaryObservation( ObservationLib.Observation memory _observation, PeriodOffsetRelativeTimestamp _time ) private pure returns (ObservationLib.Observation memory) { return ObservationLib.Observation({ cumulativeBalance: _extrapolateFromBalance(_observation, _time), balance: _observation.balance, timestamp: PeriodOffsetRelativeTimestamp.unwrap(_time) }); } /** * @notice Looks up the next observation index to write to in the circular buffer. * @dev If the current time is in the same period as the newest observation, we overwrite it. * @dev If the current time is in a new period, we increment the index and write a new observation. * @param PERIOD_LENGTH The length of an overwrite period * @param PERIOD_OFFSET The offset of the first period * @param _observations The circular buffer of observations * @param _accountDetails The account details to query with * @return index The index of the next observation slot to overwrite * @return newestObservation The newest observation in the circular buffer * @return isNew True if the observation slot is new, false if we're overwriting */ function _getNextObservationIndex( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, ObservationLib.Observation[MAX_CARDINALITY] storage _observations, AccountDetails memory _accountDetails ) private view returns (uint16 index, ObservationLib.Observation memory newestObservation, bool isNew) { uint16 newestIndex; (newestIndex, newestObservation) = getNewestObservation(_observations, _accountDetails); uint256 currentPeriod = getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, block.timestamp); uint256 newestObservationPeriod = getTimestampPeriod( PERIOD_LENGTH, PERIOD_OFFSET, PERIOD_OFFSET + uint256(newestObservation.timestamp) ); // Create a new Observation if it's the first period or the current time falls within a new period if (_accountDetails.cardinality == 0 || currentPeriod > newestObservationPeriod) { return (_accountDetails.nextObservationIndex, newestObservation, true); } // Otherwise, we're overwriting the current newest Observation return (newestIndex, newestObservation, false); } /** * @notice Computes the start time of the current overwrite period * @param PERIOD_LENGTH The length of an overwrite period * @param PERIOD_OFFSET The offset of the first period * @return The start time of the current overwrite period */ function _currentOverwritePeriodStartedAt( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET ) private view returns (uint256) { uint256 period = getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, block.timestamp); return getPeriodStartTime(PERIOD_LENGTH, PERIOD_OFFSET, period); } /** * @notice Calculates the next cumulative balance using a provided Observation and timestamp. * @param _observation The observation to extrapolate from * @param _offsetTimestamp The timestamp to extrapolate to * @return cumulativeBalance The cumulative balance at the timestamp */ function _extrapolateFromBalance( ObservationLib.Observation memory _observation, PeriodOffsetRelativeTimestamp _offsetTimestamp ) private pure returns (uint128) { // new cumulative balance = provided cumulative balance (or zero) + (current balance * elapsed seconds) unchecked { return uint128( uint256(_observation.cumulativeBalance) + uint256(_observation.balance) * (PeriodOffsetRelativeTimestamp.unwrap(_offsetTimestamp) - _observation.timestamp) ); } } /** * @notice Computes the overwrite period start time given the current time * @param PERIOD_LENGTH The length of an overwrite period * @param PERIOD_OFFSET The offset of the first period * @return The start time for the current overwrite period. */ function currentOverwritePeriodStartedAt( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET ) internal view returns (uint256) { return _currentOverwritePeriodStartedAt(PERIOD_LENGTH, PERIOD_OFFSET); } /** * @notice Calculates the period a timestamp falls within. * @dev Timestamp prior to the PERIOD_OFFSET are considered to be in period 0. * @param PERIOD_LENGTH The length of an overwrite period * @param PERIOD_OFFSET The offset of the first period * @param _timestamp The timestamp to calculate the period for * @return period The period */ function getTimestampPeriod( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, uint256 _timestamp ) internal pure returns (uint256) { if (_timestamp <= PERIOD_OFFSET) { return 0; } return (_timestamp - PERIOD_OFFSET) / uint256(PERIOD_LENGTH); } /** * @notice Calculates the start timestamp for a period * @param PERIOD_LENGTH The period length to use to calculate the period * @param PERIOD_OFFSET The period offset to use to calculate the period * @param _period The period to check * @return _timestamp The timestamp at which the period starts */ function getPeriodStartTime( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, uint256 _period ) internal pure returns (uint256) { return _period * PERIOD_LENGTH + PERIOD_OFFSET; } /** * @notice Calculates the last timestamp for a period * @param PERIOD_LENGTH The period length to use to calculate the period * @param PERIOD_OFFSET The period offset to use to calculate the period * @param _period The period to check * @return _timestamp The timestamp at which the period ends */ function getPeriodEndTime( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, uint256 _period ) internal pure returns (uint256) { return (_period + 1) * PERIOD_LENGTH + PERIOD_OFFSET; } /** * @notice Looks up the newest observation before or at a given timestamp. * @dev If an observation is available at the target time, it is returned. Otherwise, the newest observation before the target time is returned. * @param PERIOD_OFFSET The period offset to use to calculate the period * @param _observations The circular buffer of observations * @param _accountDetails The account details to query with * @param _targetTime The timestamp to look up * @return prevOrAtObservation The observation */ function getPreviousOrAtObservation( uint32 PERIOD_OFFSET, ObservationLib.Observation[MAX_CARDINALITY] storage _observations, AccountDetails memory _accountDetails, uint256 _targetTime ) internal view returns (ObservationLib.Observation memory prevOrAtObservation) { if (_targetTime < PERIOD_OFFSET) { return ObservationLib.Observation({ cumulativeBalance: 0, balance: 0, timestamp: 0 }); } uint256 offsetTargetTime = _targetTime - PERIOD_OFFSET; // if this is for an overflowed time period, return 0 if (offsetTargetTime > type(uint32).max) { return ObservationLib.Observation({ cumulativeBalance: 0, balance: 0, timestamp: type(uint32).max }); } prevOrAtObservation = _getPreviousOrAtObservation( _observations, _accountDetails, PeriodOffsetRelativeTimestamp.wrap(uint32(offsetTargetTime)) ); } /** * @notice Looks up the newest observation before or at a given timestamp. * @dev If an observation is available at the target time, it is returned. Otherwise, the newest observation before the target time is returned. * @param _observations The circular buffer of observations * @param _accountDetails The account details to query with * @param _offsetTargetTime The timestamp to look up (offset by the period offset) * @return prevOrAtObservation The observation */ function _getPreviousOrAtObservation( ObservationLib.Observation[MAX_CARDINALITY] storage _observations, AccountDetails memory _accountDetails, PeriodOffsetRelativeTimestamp _offsetTargetTime ) private view returns (ObservationLib.Observation memory prevOrAtObservation) { // If there are no observations, return a zeroed observation if (_accountDetails.cardinality == 0) { return ObservationLib.Observation({ cumulativeBalance: 0, balance: 0, timestamp: 0 }); } uint16 oldestTwabIndex; (oldestTwabIndex, prevOrAtObservation) = getOldestObservation(_observations, _accountDetails); // if the requested time is older than the oldest observation if (PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime) < prevOrAtObservation.timestamp) { // if the user didn't have any activity prior to the oldest observation, then we know they had a zero balance if (_accountDetails.cardinality < MAX_CARDINALITY) { return ObservationLib.Observation({ cumulativeBalance: 0, balance: 0, timestamp: PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime) }); } else { // if we are missing their history, we must revert revert InsufficientHistory( _offsetTargetTime, PeriodOffsetRelativeTimestamp.wrap(prevOrAtObservation.timestamp) ); } } // We know targetTime >= oldestObservation.timestamp because of the above if statement, so we can return here. if (_accountDetails.cardinality == 1) { return prevOrAtObservation; } // Find the newest observation ( uint16 newestTwabIndex, ObservationLib.Observation memory afterOrAtObservation ) = getNewestObservation(_observations, _accountDetails); // if the target time is at or after the newest, return it if (PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime) >= afterOrAtObservation.timestamp) { return afterOrAtObservation; } // if we know there is only 1 observation older than the newest if (_accountDetails.cardinality == 2) { return prevOrAtObservation; } // Otherwise, we perform a binarySearch to find the observation before or at the timestamp (prevOrAtObservation, oldestTwabIndex, afterOrAtObservation, newestTwabIndex) = ObservationLib .binarySearch( _observations, newestTwabIndex, oldestTwabIndex, PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime), _accountDetails.cardinality ); // If the afterOrAt is at, we can skip a temporary Observation computation by returning it here if (afterOrAtObservation.timestamp == PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime)) { return afterOrAtObservation; } return prevOrAtObservation; } /** * @notice Checks if the given timestamp is safe to perform a historic balance lookup on. * @dev A timestamp is safe if it is before the current overwrite period * @param PERIOD_LENGTH The period length to use to calculate the period * @param PERIOD_OFFSET The period offset to use to calculate the period * @param _time The timestamp to check * @return isSafe Whether or not the timestamp is safe */ function hasFinalized( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, uint256 _time ) internal view returns (bool) { return _hasFinalized(PERIOD_LENGTH, PERIOD_OFFSET, _time); } /** * @notice Checks if the given timestamp is safe to perform a historic balance lookup on. * @dev A timestamp is safe if it is on or before the current overwrite period start time * @param PERIOD_LENGTH The period length to use to calculate the period * @param PERIOD_OFFSET The period offset to use to calculate the period * @param _time The timestamp to check * @return isSafe Whether or not the timestamp is safe */ function _hasFinalized( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, uint256 _time ) private view returns (bool) { // It's safe if equal to the overwrite period start time, because the cumulative balance won't be impacted return _time <= _currentOverwritePeriodStartedAt(PERIOD_LENGTH, PERIOD_OFFSET); } /** * @notice Checks if the given timestamp is safe to perform a historic balance lookup on. * @param PERIOD_LENGTH The period length to use to calculate the period * @param PERIOD_OFFSET The period offset to use to calculate the period * @param _timestamp The timestamp to check */ modifier requireFinalized( uint32 PERIOD_LENGTH, uint32 PERIOD_OFFSET, uint256 _timestamp ) { // The current period can still be changed; so the start of the period marks the beginning of unsafe timestamps. uint256 overwritePeriodStartTime = _currentOverwritePeriodStartedAt( PERIOD_LENGTH, PERIOD_OFFSET ); // timestamp == overwritePeriodStartTime doesn't matter, because the cumulative balance won't be impacted if (_timestamp > overwritePeriodStartTime) { revert TimestampNotFinalized(_timestamp, overwritePeriodStartTime); } _; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "ring-buffer-lib/RingBufferLib.sol"; /** * @dev Sets max ring buffer length in the Account.observations Observation list. * As users transfer/mint/burn tickets new Observation checkpoints are recorded. * The current `MAX_CARDINALITY` guarantees a one year minimum, of accurate historical lookups. * @dev The user Account.Account.cardinality parameter can NOT exceed the max cardinality variable. * Preventing "corrupted" ring buffer lookup pointers and new observation checkpoints. */ uint16 constant MAX_CARDINALITY = 17520; // with min period of 1 hour, this allows for minimum two years of history /** * @title PoolTogether V5 Observation Library * @author PoolTogether Inc. & G9 Software Inc. * @notice This library allows one to store an array of timestamped values and efficiently search them. * @dev Largely pulled from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/c05a0e2c8c08c460fb4d05cfdda30b3ad8deeaac/contracts/libraries/Oracle.sol */ library ObservationLib { /** * @notice Observation, which includes an amount and timestamp. * @param cumulativeBalance the cumulative time-weighted balance at `timestamp`. * @param balance `balance` at `timestamp`. * @param timestamp Recorded `timestamp`. */ struct Observation { uint128 cumulativeBalance; uint96 balance; uint32 timestamp; } /** * @notice Fetches Observations `beforeOrAt` and `afterOrAt` a `_target`, eg: where [`beforeOrAt`, `afterOrAt`] is satisfied. * The result may be the same Observation, or adjacent Observations. * @dev The _target must fall within the boundaries of the provided _observations. * Meaning the _target must be: older than the most recent Observation and younger, or the same age as, the oldest Observation. * @dev If `_newestObservationIndex` is less than `_oldestObservationIndex`, it means that we've wrapped around the circular buffer. * So the most recent observation will be at `_oldestObservationIndex + _cardinality - 1`, at the beginning of the circular buffer. * @param _observations List of Observations to search through. * @param _newestObservationIndex Index of the newest Observation. Right side of the circular buffer. * @param _oldestObservationIndex Index of the oldest Observation. Left side of the circular buffer. * @param _target Timestamp at which we are searching the Observation. * @param _cardinality Cardinality of the circular buffer we are searching through. * @return beforeOrAt Observation recorded before, or at, the target. * @return beforeOrAtIndex Index of observation recorded before, or at, the target. * @return afterOrAt Observation recorded at, or after, the target. * @return afterOrAtIndex Index of observation recorded at, or after, the target. */ function binarySearch( Observation[MAX_CARDINALITY] storage _observations, uint24 _newestObservationIndex, uint24 _oldestObservationIndex, uint32 _target, uint16 _cardinality ) internal view returns ( Observation memory beforeOrAt, uint16 beforeOrAtIndex, Observation memory afterOrAt, uint16 afterOrAtIndex ) { uint256 leftSide = _oldestObservationIndex; uint256 rightSide = _newestObservationIndex < leftSide ? leftSide + _cardinality - 1 : _newestObservationIndex; uint256 currentIndex; while (true) { // We start our search in the middle of the `leftSide` and `rightSide`. // After each iteration, we narrow down the search to the left or the right side while still starting our search in the middle. currentIndex = (leftSide + rightSide) / 2; beforeOrAtIndex = uint16(RingBufferLib.wrap(currentIndex, _cardinality)); beforeOrAt = _observations[beforeOrAtIndex]; uint32 beforeOrAtTimestamp = beforeOrAt.timestamp; afterOrAtIndex = uint16(RingBufferLib.nextIndex(currentIndex, _cardinality)); afterOrAt = _observations[afterOrAtIndex]; bool targetAfterOrAt = beforeOrAtTimestamp <= _target; // Check if we've found the corresponding Observation. if (targetAfterOrAt && _target <= afterOrAt.timestamp) { break; } // If `beforeOrAtTimestamp` is greater than `_target`, then we keep searching lower. To the left of the current index. if (!targetAfterOrAt) { rightSide = currentIndex - 1; } else { // Otherwise, we keep searching higher. To the right of the current index. leftSide = currentIndex + 1; } } } }
// 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; 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 "../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 { 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 { 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 "./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 "./ud60x18/Casting.sol"; import "./ud60x18/Constants.sol"; import "./ud60x18/Conversions.sol"; import "./ud60x18/Errors.sol"; import "./ud60x18/Helpers.sol"; import "./ud60x18/Math.sol"; import "./ud60x18/ValueType.sol";
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; /** * NOTE: There is a difference in meaning between "cardinality" and "count": * - cardinality is the physical size of the ring buffer (i.e. max elements). * - count is the number of elements in the buffer, which may be less than cardinality. */ library RingBufferLib { /** * @notice Returns wrapped TWAB index. * @dev In order to navigate the TWAB circular buffer, we need to use the modulo operator. * @dev For example, if `_index` is equal to 32 and the TWAB circular buffer is of `_cardinality` 32, * it will return 0 and will point to the first element of the array. * @param _index Index used to navigate through the TWAB circular buffer. * @param _cardinality TWAB buffer cardinality. * @return TWAB index. */ function wrap(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return _index % _cardinality; } /** * @notice Computes the negative offset from the given index, wrapped by the cardinality. * @dev We add `_cardinality` to `_index` to be able to offset even if `_amount` is superior to `_cardinality`. * @param _index The index from which to offset * @param _amount The number of indices to offset. This is subtracted from the given index. * @param _count The number of elements in the ring buffer * @return Offsetted index. */ function offset( uint256 _index, uint256 _amount, uint256 _count ) internal pure returns (uint256) { return wrap(_index + _count - _amount, _count); } /// @notice Returns the index of the last recorded TWAB /// @param _nextIndex The next available twab index. This will be recorded to next. /// @param _count The count of the TWAB history. /// @return The index of the last recorded TWAB function newestIndex(uint256 _nextIndex, uint256 _count) internal pure returns (uint256) { if (_count == 0) { return 0; } return wrap(_nextIndex + _count - 1, _count); } function oldestIndex(uint256 _nextIndex, uint256 _count, uint256 _cardinality) internal pure returns (uint256) { if (_count < _cardinality) { return 0; } else { return wrap(_nextIndex + _cardinality, _cardinality); } } /// @notice Computes the ring buffer index that follows the given one, wrapped by cardinality /// @param _index The index to increment /// @param _cardinality The number of elements in the Ring Buffer /// @return The next index relative to the given index. Will wrap around to 0 if the next index == cardinality function nextIndex(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return wrap(_index + 1, _cardinality); } /// @notice Computes the ring buffer index that preceeds the given one, wrapped by cardinality /// @param _index The index to increment /// @param _cardinality The number of elements in the Ring Buffer /// @return The prev index relative to the given index. Will wrap around to the end if the prev index == 0 function prevIndex(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return _index == 0 ? _cardinality - 1 : _index - 1; } }
/** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.8.19; error UpperBoundGtZero(); /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { if(_upperBound == 0) { revert UpperBoundGtZero(); } uint256 min = (type(uint256).max-_upperBound+1) % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } }
// 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; // 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 { 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 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 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 "../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 { 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": [ "ds-test/=lib/forge-std/lib/ds-test/src/", "forge-std/=lib/forge-std/src/", "aave-address-book/=lib/aave-address-book/src/", "chainlink/=lib/pt-v5-chainlink-vrf-v2-direct/lib/chainlink/contracts/src/v0.8/", "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/", "openzeppelin-contracts/contracts/=lib/openzeppelin-contracts/contracts/", "prb-math/=lib/pt-v5-cgda-liquidator/lib/prb-math/src/", "solidity-stringutils/=lib/solidity-stringutils/src/", "yield-daddy/=lib/yield-daddy/src/", "pt-v5-chainlink-vrf-v2-direct/=lib/pt-v5-chainlink-vrf-v2-direct/src/", "pt-v5-draw-auction/=lib/pt-v5-draw-auction/src/", "pt-v5-cgda-liquidator/=lib/pt-v5-cgda-liquidator/src/", "pt-v5-liquidator-interfaces/=lib/pt-v5-cgda-liquidator/lib/pt-v5-liquidator-interfaces/src/interfaces/", "pt-v5-prize-pool/=lib/pt-v5-prize-pool/src/", "pt-v5-twab-controller/=lib/pt-v5-twab-controller/src/", "pt-v5-vault/=lib/pt-v5-vault/src/", "pt-v5-vault-boost/=lib/pt-v5-vault-boost/src/", "pt-v5-vault-mock/=lib/pt-v5-vault/test/contracts/mock/", "pt-v5-claimer/=lib/pt-v5-claimer/src/", "rng/=lib/pt-v5-draw-auction/lib/pt-v5-rng-contracts/contracts/", "rng-contracts/=lib/pt-v5-draw-auction/lib/pt-v5-rng-contracts/contracts/", "remote-owner/=lib/pt-v5-draw-auction/lib/remote-owner/src/", "@aave/core-v3/=lib/aave-address-book/lib/aave-v3-core/", "@aave/periphery-v3/=lib/aave-address-book/lib/aave-v3-periphery/", "@openzeppelin/=lib/pt-v5-draw-auction/lib/openzeppelin-contracts/", "@prb/test/=lib/pt-v5-draw-auction/lib/prb-math/lib/prb-test/src/", "aave-v3-core/=lib/aave-address-book/lib/aave-v3-core/", "aave-v3-periphery/=lib/aave-address-book/lib/aave-v3-periphery/", "brokentoken/=lib/pt-v5-vault/lib/brokentoken/src/", "create3-factory/=lib/yield-daddy/lib/create3-factory/", "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/", "erc5164-interfaces/=lib/pt-v5-draw-auction/lib/erc5164-interfaces/src/", "openzeppelin/=lib/openzeppelin-contracts/contracts/", "owner-manager-contracts/=lib/pt-v5-draw-auction/lib/owner-manager-contracts/contracts/", "owner-manager/=lib/pt-v5-draw-auction/lib/owner-manager-contracts/contracts/", "prb-test/=lib/pt-v5-draw-auction/lib/prb-math/lib/prb-test/src/", "pt-v5-claimable-interface/=lib/pt-v5-claimer/lib/pt-v5-claimable-interface/src/", "pt-v5-rng-contracts/=lib/pt-v5-rng-contracts/contracts/", "pt-v5-twab-delegator/=lib/pt-v5-twab-delegator/src/", "pt-v5-twab-rewards/=lib/pt-v5-twab-rewards/src/", "ring-buffer-lib/=lib/pt-v5-prize-pool/lib/ring-buffer-lib/src/", "rng/=lib/pt-v5-draw-auction/lib/pt-v5-rng-contracts/contracts/", "solmate/=lib/pt-v5-claimer/lib/solmate/src/", "uniform-random-number/=lib/pt-v5-prize-pool/lib/uniform-random-number/src/", "weird-erc20/=lib/pt-v5-vault/lib/brokentoken/lib/weird-erc20/src/" ], "optimizer": { "enabled": true, "runs": 200, "details": { "peephole": true, "inliner": true, "deduplicate": true, "cse": true, "yul": true } }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "paris", "viaIR": true, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"contract IERC20","name":"asset_","type":"address"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"contract IERC4626","name":"yieldVault_","type":"address"},{"internalType":"contract PrizePool","name":"prizePool_","type":"address"},{"internalType":"address","name":"claimer_","type":"address"},{"internalType":"address","name":"yieldFeeRecipient_","type":"address"},{"internalType":"uint32","name":"yieldFeePercentage_","type":"uint32"},{"internalType":"address","name":"owner_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"bytes","name":"reason","type":"bytes"}],"name":"AfterClaimPrizeFailed","type":"error"},{"inputs":[{"internalType":"bytes","name":"reason","type":"bytes"}],"name":"BeforeClaimPrizeFailed","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"claimer","type":"address"}],"name":"CallerNotClaimer","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"liquidationPair","type":"address"}],"name":"CallerNotLP","type":"error"},{"inputs":[],"name":"ClaimRecipientZeroAddress","type":"error"},{"inputs":[],"name":"ClaimerZeroAddress","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"DepositMoreThanMax","type":"error"},{"inputs":[],"name":"InvalidShortString","type":"error"},{"inputs":[],"name":"LPZeroAddress","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"availableYield","type":"uint256"}],"name":"LiquidationAmountOutGTYield","type":"error"},{"inputs":[],"name":"LiquidationAmountOutZero","type":"error"},{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"prizeToken","type":"address"}],"name":"LiquidationTokenInNotPrizeToken","type":"error"},{"inputs":[{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"address","name":"vaultShare","type":"address"}],"name":"LiquidationTokenOutNotVaultShare","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"MintMoreThanMax","type":"error"},{"inputs":[],"name":"MintZeroShares","type":"error"},{"inputs":[],"name":"OwnerZeroAddress","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"allowance","type":"uint256"}],"name":"PermitAllowanceNotSet","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"PermitCallerNotOwner","type":"error"},{"inputs":[],"name":"PrizePoolZeroAddress","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"RedeemMoreThanMax","type":"error"},{"inputs":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"inputs":[],"name":"SweepZeroAssets","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"TargetTokenNotSupported","type":"error"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"address","name":"yieldVaultAsset","type":"address"}],"name":"UnderlyingAssetMismatch","type":"error"},{"inputs":[],"name":"VaultUndercollateralized","type":"error"},{"inputs":[{"internalType":"uint256","name":"requestedAssets","type":"uint256"},{"internalType":"uint256","name":"withdrawnAssets","type":"uint256"}],"name":"WithdrawAssetsLTRequested","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"WithdrawMoreThanMax","type":"error"},{"inputs":[],"name":"WithdrawZeroAssets","type":"error"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"yieldFeeShares","type":"uint256"}],"name":"YieldFeeGTAvailableShares","type":"error"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"availableYield","type":"uint256"}],"name":"YieldFeeGTAvailableYield","type":"error"},{"inputs":[{"internalType":"uint256","name":"yieldFeePercentage","type":"uint256"},{"internalType":"uint256","name":"maxYieldFeePercentage","type":"uint256"}],"name":"YieldFeePercentageGtePrecision","type":"error"},{"inputs":[],"name":"YieldVaultZeroAddress","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":"claimer","type":"address"}],"name":"ClaimerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tokenOut","type":"address"},{"indexed":true,"internalType":"address","name":"liquidationPair","type":"address"}],"name":"LiquidationPairSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"MintYieldFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20","name":"asset","type":"address"},{"indexed":false,"internalType":"string","name":"name","type":"string"},{"indexed":false,"internalType":"string","name":"symbol","type":"string"},{"indexed":false,"internalType":"contract TwabController","name":"twabController","type":"address"},{"indexed":true,"internalType":"contract IERC4626","name":"yieldVault","type":"address"},{"indexed":true,"internalType":"contract PrizePool","name":"prizePool","type":"address"},{"indexed":false,"internalType":"address","name":"claimer","type":"address"},{"indexed":false,"internalType":"address","name":"yieldFeeRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"yieldFeePercentage","type":"uint256"},{"indexed":false,"internalType":"address","name":"owner","type":"address"}],"name":"NewVault","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipOffered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"components":[{"internalType":"bool","name":"useBeforeClaimPrize","type":"bool"},{"internalType":"bool","name":"useAfterClaimPrize","type":"bool"},{"internalType":"contract IVaultHooks","name":"implementation","type":"address"}],"indexed":true,"internalType":"struct VaultHooks","name":"hooks","type":"tuple"}],"name":"SetHooks","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Sponsor","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"Sweep","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":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"yieldFeePercentage","type":"uint256"}],"name":"YieldFeePercentageSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"yieldFeeRecipient","type":"address"}],"name":"YieldFeeRecipientSet","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","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":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"availableYieldBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"availableYieldFeeBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"claimOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_winner","type":"address"},{"internalType":"uint8","name":"_tier","type":"uint8"},{"internalType":"uint32","name":"_prizeIndex","type":"uint32"},{"internalType":"uint96","name":"_fee","type":"uint96"},{"internalType":"address","name":"_feeRecipient","type":"address"}],"name":"claimPrize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimer","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_assets","type":"uint256"}],"name":"convertToShares","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":[{"internalType":"uint256","name":"_assets","type":"uint256"},{"internalType":"address","name":"_receiver","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_assets","type":"uint256"},{"internalType":"address","name":"_owner","type":"address"},{"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":"depositWithPermit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"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":[{"internalType":"address","name":"_account","type":"address"}],"name":"getHooks","outputs":[{"components":[{"internalType":"bool","name":"useBeforeClaimPrize","type":"bool"},{"internalType":"bool","name":"useAfterClaimPrize","type":"bool"},{"internalType":"contract IVaultHooks","name":"implementation","type":"address"}],"internalType":"struct VaultHooks","name":"","type":"tuple"}],"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":[{"internalType":"address","name":"_tokenOut","type":"address"},{"internalType":"address","name":"liquidationPair_","type":"address"}],"name":"isLiquidationPair","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isVaultCollateralized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"liquidatableBalanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidationPair","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"},{"internalType":"address","name":"_receiver","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"mintYieldFee","outputs":[],"stateMutability":"nonpayable","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":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"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":[{"internalType":"uint256","name":"_assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"prizePool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"},{"internalType":"address","name":"_receiver","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"claimer_","type":"address"}],"name":"setClaimer","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bool","name":"useBeforeClaimPrize","type":"bool"},{"internalType":"bool","name":"useAfterClaimPrize","type":"bool"},{"internalType":"contract IVaultHooks","name":"implementation","type":"address"}],"internalType":"struct VaultHooks","name":"hooks","type":"tuple"}],"name":"setHooks","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"liquidationPair_","type":"address"}],"name":"setLiquidationPair","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"yieldFeePercentage_","type":"uint32"}],"name":"setYieldFeePercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"yieldFeeRecipient_","type":"address"}],"name":"setYieldFeeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_assets","type":"uint256"}],"name":"sponsor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sweep","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"targetOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"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":[{"internalType":"address","name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"_receiver","type":"address"},{"internalType":"address","name":"_tokenOut","type":"address"},{"internalType":"uint256","name":"_amountOut","type":"uint256"}],"name":"transferTokensOut","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"twabController","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenIn","type":"address"},{"internalType":"uint256","name":"_amountIn","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"verifyTokensIn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_assets","type":"uint256"},{"internalType":"address","name":"_receiver","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"yieldFeePercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldFeeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldFeeShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"yieldVault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
61020080604052346200077e5762004cbe803803809162000021828562000bdc565b8339810190610120818303126200077e578051906001600160a01b03821682036200077e5760208101516001600160401b0381116200077e57836200006891830162000c41565b604082015190936001600160401b0382116200077e576200008b91830162000c41565b6060820151936001600160a01b03851685036200077e576080830151906001600160a01b03821682036200077e57620000c760a0850162000c8e565b91620000d660c0860162000c8e565b9360e08601519563ffffffff871687036200077e57610100620000fa910162000c8e565b90604051620001098162000bc0565b60018152603160f81b602082015284516001600160401b0381116200078357600354600181811c9116801562000bb5575b602082101462000a9857601f811162000b4f575b50806020601f821160011462000ac55760009162000ab9575b508160011b916000199060031b1c1916176003555b81516001600160401b0381116200078357600454600181811c9116801562000aae575b602082101462000a9857601f811162000a32575b50806020601f8211600114620009a8576000916200099c575b508160011b916000199060031b1c1916176004555b620001ec8562000d9e565b61012052620001fb8162000f25565b6101405284516020860120908160e0526020815191012080610100524660a052604051917f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f6020840152604083015260608201524660808201523060a082015260a081528060c081011060018060401b0360c083011117620007835760c081810160405281516020830120608052309052600980546001600160a01b038581166001600160a01b031983168117909355167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a36001600160a01b038a16156200098857506001600160a01b0383161562000976576001600160a01b0382161562000964576040516338d52e0f60e01b808252906020816004816001600160a01b038f165afa908115620007ea5760009162000922575b506001600160a01b03908116908a16036200088657506001600160a01b038516156200087457600b80546001600160a01b0319166001600160a01b03871617905562000380886200107c565b90156200086b575b6101805261016088905260405163b0812d7b60e01b8152966020886004816001600160a01b0388165afa978815620007ea576000986200081a575b506101a08890526101c08a90526101e0849052600d80546001600160a01b0319166001600160a01b038916179055633b9aca0063ffffffff8216811115620007f65750600a805463ffffffff60a01b191660a083901b63ffffffff60a01b16179055604051636eb1769f60e11b81523060048201526001600160a01b038b166024820152602081806044810103816001600160a01b038e165afa908115620007ea57600091620007af575b5060001981018111620007995760405163095ea7b360e01b60208201526001600160a01b038c16602482015260001990910160448083019190915281526001600160401b0360808201908111908211176200078357806080620005419201604052620004dd6080820162000bc0565b602060808201527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c656460a082015260806000808d84519082602087019160018060a01b03165af19101906200053062000cca565b906001600160a01b038d1662000cff565b805190811591821562000758575b50501562000700577f298dea63564023ccf1449f62907979461f5360d87bb47b24100a68525ba5bffc966200059d96620005ac63ffffffff94604051998a9960e08b5260e08b019062000ca3565b9089820360208b015262000ca3565b6001600160a01b039a8b166040890152908a1660608801529089166080870152911660a085015290861660c084015290851696851695909416930390a4604051613bb8908162001106823960805181612a49015260a05181612b15015260c05181612a13015260e05181612a9801526101005181612abe015261012051816114690152610140518161149201526101605181818161115201528181611a3001528181611cc101528181611d4701526132e801526101805181611e9801526101a051818181610c5201528181610eb001528181612e7201528181612f5a0152818161367e015281816139750152613ab201526101c051818181610f25015281816111c001528181611dab01528181612f030152818161317b0152818161334c0152818161374f0152818161382c01526138d201526101e051818181610905015281816117550152818161180701526120360152f35b60405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608490fd5b81925090602091810103126200077e576020015180151581036200077e5738806200054f565b600080fd5b634e487b7160e01b600052604160045260246000fd5b634e487b7160e01b600052601160045260246000fd5b906020823d602011620007e1575b81620007cc6020938362000bdc565b81010312620007de575051386200046e565b80fd5b3d9150620007bd565b6040513d6000823e3d90fd5b6044925063ffffffff604051926338747b7960e21b84521660048301526024820152fd5b6020989198813d60201162000862575b81620008396020938362000bdc565b810103126200085e5751906001600160a01b0382168203620007de57509638620003c3565b5080fd5b3d91506200082a565b50601262000388565b604051634d9808e160e11b8152600490fd5b604051908152886020826004816001600160a01b038f165afa918215620007ea57600092620008de575b5060405163327f209f60e21b81526001600160a01b03918216600482015291166024820152604490fd5b0390fd5b90916020823d60201162000919575b81620008fc6020938362000bdc565b81010312620007de5750620009119062000c8e565b9082620008b0565b3d9150620008ed565b906020823d6020116200095b575b816200093f6020938362000bdc565b81010312620007de5750620009549062000c8e565b3862000334565b3d915062000930565b604051630962257960e11b8152600490fd5b6040516305d872f360e21b8152600490fd5b60c06004916307877e8560e01b8282015201fd5b905083015138620001cc565b6004600090815292507f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b905b601f198316841062000a19576001935082601f19811610620009ff575b5050811b01600455620001e1565b85015160001960f88460031b161c191690553880620009f1565b85810151825560209384019360019092019101620009d4565b60046000527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b601f830160051c81016020841062000a90575b601f830160051c8201811062000a83575050620001b3565b6000815560010162000a6b565b508062000a6b565b634e487b7160e01b600052602260045260246000fd5b90607f16906200019f565b90508601513862000167565b6003600090815292507fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b905b601f198316841062000b36576001935082601f1981161062000b1c575b5050811b016003556200017c565b88015160001960f88460031b161c19169055388062000b0e565b8881015182556020938401936001909201910162000af1565b60036000527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b601f830160051c81016020841062000bad575b601f830160051c8201811062000ba05750506200014e565b6000815560010162000b88565b508062000b88565b90607f16906200013a565b604081019081106001600160401b038211176200078357604052565b601f909101601f19168101906001600160401b038211908210176200078357604052565b6001600160401b0381116200078357601f01601f191660200190565b60005b83811062000c305750506000910152565b818101518382015260200162000c1f565b81601f820112156200077e57805162000c5a8162000c00565b9262000c6a604051948562000bdc565b818452602082840101116200077e5762000c8b916020808501910162000c1c565b90565b51906001600160a01b03821682036200077e57565b9060209162000cbe8151809281855285808601910162000c1c565b601f01601f1916010190565b3d1562000cfa573d9062000cde8262000c00565b9162000cee604051938462000bdc565b82523d6000602084013e565b606090565b9192901562000d64575081511562000d15575090565b3b1562000d1f5790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b82519091501562000d785750805190602001fd5b60405162461bcd60e51b815260206004820152908190620008da90602483019062000ca3565b8051602091908281101562000e00575090601f82511162000ddc578082519201519080831062000dcd57501790565b82600019910360031b1b161790565b620008da60405192839263305a27a960e01b84526004840152602483019062000ca3565b6001600160401b03811162000783576005928354926001938481811c9116801562000f1a575b8382101462000a9857601f811162000ee3575b5081601f841160011462000e79575092829391839260009462000e6d575b50501b916000199060031b1c191617905560ff90565b01519250388062000e57565b919083601f1981168760005284600020946000905b8883831062000ec8575050501062000eae575b505050811b01905560ff90565b015160001960f88460031b161c1916905538808062000ea1565b85870151885590960195948501948793509081019062000e8e565b8560005284601f846000209201871c820191601f8601881c015b82811062000f0d57505062000e39565b6000815501859062000efd565b90607f169062000e26565b80516020908181101562000f525750601f82511162000ddc578082519201519080831062000dcd57501790565b906001600160401b0382116200078357600654926001938481811c9116801562001071575b8382101462000a9857601f811162001037575b5081601f841160011462000fcb575092829391839260009462000fbf575b50501b916000199060031b1c19161760065560ff90565b01519250388062000fa8565b919083601f198116600660005284600020946000905b888383106200101c575050501062001002575b505050811b0160065560ff90565b015160001960f88460031b161c1916905538808062000ff4565b85870151885590960195948501948793509081019062000fe1565b600660005284601f84600020920160051c820191601f860160051c015b8281106200106457505062000f8a565b6000815501859062001054565b90607f169062000f77565b90604051602081019063313ce56760e01b8252600481526200109e8162000bc0565b5160009384928392916001600160a01b03165afa620010bc62000cca565b9080620010f8575b620010cf575b508190565b602081805181010312620010f4576020015160ff8111620010ca576001925060ff1690565b8280fd5b50602081511015620010c456fe6040608081526004908136101561001557600080fd5b600091823560e01c806301e1d1141461244a57806306fdde03146123a057806307a2d13a14611c57578063095ea7b3146123765780630a28a477146123455780630d1e5255146123285780630f2630e8146122fa57806318160ddd146122dd5780631b5719241461228857806323b872dd1461224b57806325fa66e0146121bb5780632895cace14611ebc578063313ce56714611e7e57806335faa41614611d0d5780633644e51514611cf057806338d52e0f14611cac5780633950935114611c5c578063402d267d14610b755780634cdad50614611c575780634e71e0c814611ba157806350921b23146119ee57806363003b161461197457806363e4db75146118a5578063649f23941461187c5780636e553f65146118525780636f711fb214611833578063700f04ef146117e557806370a08231146105c5578063715018a614611784578063719ce73e146117405780637cc99d3f1461157e5780637ecebe001461154657806384b0196e146114515780638da5cb5b1461142857806394bf804d146110e657806395d89b4114610ffa578063a457c2d714610f54578063a7f8a5e214610f10578063a9059cbb14610edf578063b0812d7b14610e9b578063b0fcf62614610e75578063b3d7f6b914610e44578063b460af9414610d70578063b5a7efe514610d53578063b6cce5e214610c0b578063ba08765214610b7a578063c63d75b614610b75578063c6e6f592146103a1578063c78c72c114610ab6578063c8576e611461089a578063cdfb58321461080c578063ce96cb77146107d2578063d379be23146107a9578063d505accf146105f2578063d905777e146105c5578063dd62ed3e14610577578063de03f408146104e5578063e16777c1146104bd578063e30c397814610494578063e4e243ac146103d3578063edb8eb80146103a6578063ef8b30f7146103a15763f2fde38b146102d657600080fd5b3461039d57602036600319011261039d576102ef6124de565b6009546001600160a01b0391906103099083163314612cf1565b1691821561034c575050600a80546001600160a01b031916821790557f239a2ddded15777fa246aed5f7e1a9bc69a39d4eb4a397034d1d85766cca7d4c8280a280f35b906020608492519162461bcd60e51b8352820152602560248201527f4f776e61626c652f70656e64696e674f776e65722d6e6f742d7a65726f2d6164604482015264647265737360d81b6064820152fd5b8280fd5b612585565b5050346103cf57816003193601126103cf57600d5490516001600160a01b039091168152602090f35b5080fd5b5082346104915760203660031901126104915750803563ffffffff81169182820361048c5761040d60018060a01b03600954163314612cf1565b633b9aca008084101561047057600a805463ffffffff60a01b191660a085901b63ffffffff60a01b161790558451848152602090859087907fefb99600b8c2baadc10ee4fe77c625b379acb4c29fbb0b90a5f17652d7de0341908490a151908152f35b91509160449351926338747b7960e21b84528301526024820152fd5b600080fd5b80fd5b5050346103cf57816003193601126103cf57600a5490516001600160a01b039091168152602090f35b5050346103cf57816003193601126103cf5760209063ffffffff600a5460a01c169051908152f35b5050346103cf5760203660031901126103cf5790816060926105056124de565b9280828051610513816125ee565b828152826020820152015260018060a01b038094168152600f602052209181519261053d846125ee565b5460ff81161515938481528284602083019260ff8560081c1615158452019260101c16825283519485525115156020850152511690820152f35b5050346103cf57806003193601126103cf576020916105946124de565b8261059d6124f4565b6001600160a01b03928316845260018652922091166000908152908352819020549051908152f35b5050346103cf5760203660031901126103cf576020906105eb6105e66124de565b612e43565b9051908152f35b508290346103cf5760e03660031901126103cf5761060e6124de565b6106166124f4565b906044359260643560843560ff8116810361048c578142116107665760018060a01b0390818516928389526007602052898920908154916001830190558a519060208201927f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98452868d840152858a1660608401528a608084015260a083015260c082015260c0815260e0810181811067ffffffffffffffff821117610751578b525190206106f9916106f1916106cb612a10565b908c519161190160f01b83526002830152602282015260c43591604260a4359220612981565b919091612867565b160361070e575061070b9394506126cd565b80f35b606490602087519162461bcd60e51b8352820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152fd5b604187634e487b7160e01b6000525260246000fd5b875162461bcd60e51b8152602081850152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606490fd5b5050346103cf57816003193601126103cf57600b5490516001600160a01b039091168152602090f35b5050346103cf5760203660031901126103cf576020906105eb6107f66105e66124de565b6107fe612f3f565b610806612ee8565b91613120565b508290346103cf5760203660031901126103cf576108286124de565b6009546001600160a01b0391906108429083163314612cf1565b1690811561088c5750807fa04eca05f1c4f5674beaad80f345070124aa2192abced410b9b227c0c04e755a602094826001600160601b0360a01b600b541617600b55519380a28152f35b8351634d9808e160e11b8152fd5b50903461039d57606036600319011261039d576108b56124de565b9160443567ffffffffffffffff808211610ab25736602383011215610ab25781830135908111610ab25736910160240111610aae57600c546001600160a01b039190821633819003610a815750817f00000000000000000000000000000000000000000000000000000000000000001691835194636877812560e11b80875260209687818681895afa908115610a77579084918a91610a5a575b5016838316036109c4575050508291604485928795519586938492630eedfb4560e41b8452309084015260243560248401525af19081156109bb5750610993578280f35b813d83116109b4575b6109a68183612688565b8101031261048c5738808280f35b503d61099c565b513d85823e3d90fd5b958088959293978588518095819382525afa948515610a4f5794610a1c575b50509251630c0760c160e21b81526001600160a01b039384169181019182529390911691909116602082015281906040010390fd5b0390fd5b610a1894509081610a4192903d10610a48575b610a398183612688565b810190612d3d565b92866109e3565b503d610a2f565b8651903d90823e3d90fd5b610a719150893d8b11610a4857610a398183612688565b3861094f565b87513d8b823e3d90fd5b83516317140eff60e11b8152339281019283526001600160a01b0390911660208301529081906040010390fd5b8380fd5b8580fd5b50903461039d57606036600319011261039d57338352600f60205280832091359081151580920361048c5782549060243580151580910361048c57604435946001600160a01b03861693848703610b715760609662010000600160b01b039060101b169060ff87169069ffffffffffffffffffff60b01b161761ff008460081b16171790558151938452602084015282015220337f5eaf51436f308830fc57b00bb6843675b383bce9b2c669e1b9ce60de8bbb9e8e8380a380f35b8780fd5b61250a565b5091346104915750610b8b36612550565b93610b9885939293612e43565b8211610bcd5750926105eb91602094610baf612f3f565b92610bc6610bbb612ee8565b858110159584613120565b923361364e565b610a18848693610bdc85612e43565b9151636c6e33c560e01b81526001600160a01b0390951693850193845260208401526040830152829160600190565b50903461039d576020928360031936011261049157823592610c2e333386613299565b5082516316bef07560e31b8152308282019081523360208201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116939290918890829081906040010381875afa908115610d495790600192918691610d2c575b501603610cd8575b505050805182815282848201527f64939930c3fd0a1fe9e7fb9810272db7730a0f02b900972787bcb79fb6fd3d2d823392a251908152f35b813b1561039d578291602483928651948593849263766c4f3760e01b845233908401525af18015610d2257610d0e575b80610ca0565b610d188291612620565b6104915780610d08565b83513d84823e3d90fd5b610d439150893d8b11610a4857610a398183612688565b38610c98565b86513d87823e3d90fd5b5050346103cf57816003193601126103cf576020906105eb612d5c565b508290346103cf57610d8136612550565b9390610d8f6107f686612e43565b8311610e02579082610dc392610da3612f3f565b610dab612ee8565b81811080159550610df0575050819687915b3361364e565b90808210610dd5576020848651908152f35b845163a253e87960e01b815292830152602482015260449150fd5b610dfa9184612f96565b968791610dbd565b505083610a1891610e156107f686612e43565b91516390bb24b560e01b81526001600160a01b0390951693850193845260208401526040830152829160600190565b50913461049157602036600319011261049157506105eb602092610e66612f3f565b610e6e612ee8565b91356130f3565b5050346103cf5760203660031901126103cf576020906105eb610e966124de565b613237565b5050346103cf57816003193601126103cf57517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b5050346103cf57806003193601126103cf57602090610f09610eff6124de565b6024359033613aa6565b5160018152f35b5050346103cf57816003193601126103cf57517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b508234610491578260031936011261049157610f6e6124de565b91836024359233815260016020522060018060a01b038416600052602052836000205490828210610fa957602085610f0985850387336126cd565b608490602086519162461bcd60e51b8352820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152fd5b50913461049157806003193601126104915750805190600092805461101e816125b4565b808552916001918083169081156110be5750600114611060575b50505061104a8261105c940383612688565b51918291602083526020830190612467565b0390f35b600090815294507f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b8286106110a65750505061104a82602061105c9582010194611038565b80546020878701810191909152909501948101611089565b61105c97508693506020925061104a94915060ff191682840152151560051b82010194611038565b509134610491578160031936011261049157508135906111046124f4565b61110c612f3f565b61111d611117612ee8565b82612db7565b6111268161314d565b84116113ea575082156113da5781516370a0823160e01b815230818601526020946001600160a01b03917f00000000000000000000000000000000000000000000000000000000000000008316908781602481855afa9081156113cf579088929160009161139f575b50808811611268575b50508451636e553f6560e01b81529182018681523060208201528290819060400103816000867f0000000000000000000000000000000000000000000000000000000000000000165af1801561125d57908691611234575b50506111fc848361396b565b825191848352848684015216907fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7833392a351908152f35b813d8311611256575b6112478183612688565b8101031261048c5784386111f0565b503d61123d565b84513d6000823e3d90fd5b6112f9925060009080611395575b50801561138d57905b6000808851938b8501906323b872dd60e01b82523360248701523060448701526064860152606485526112b185612650565b8951946112bd8661266c565b8c86527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648d870152519082855af16112f3612e03565b916135b5565b805187811591821561136d575b505090501561131757853880611198565b835162461bcd60e51b8152908101869052602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608490fd5b838092935001031261048c57860151801515810361048c57808738611306565b50869061127f565b9050870338611276565b919282813d83116113c8575b6113b58183612688565b810103126104915750908791513861118f565b503d6113ab565b86513d6000823e3d90fd5b815163b31accb760e01b81528490fd5b610a1883856113f9889461314d565b9151634acfb82760e11b81526001600160a01b0390951693850193845260208401526040830152829160600190565b5050346103cf57816003193601126103cf5760095490516001600160a01b039091168152602090f35b5050346103cf57816003193601126103cf579061148d7f0000000000000000000000000000000000000000000000000000000000000000612b3b565b6114b67f0000000000000000000000000000000000000000000000000000000000000000612c37565b918351916114c383612634565b8183526114f88551958695600f60f81b87526114eb60209460e0868a015260e0890190612467565b9187830390880152612467565b904660608601523060808601528260a086015284820360c08601528080855193848152019401925b82811061152f57505050500390f35b835185528695509381019392810192600101611520565b5050346103cf5760203660031901126103cf5760209181906001600160a01b0361156e6124de565b1681526007845220549051908152f35b509190346103cf5760803660031901126103cf5761159a6124de565b506115a36124f4565b6001600160a01b039060443582811680820361048c5760643593600c541680330361171357506115e26115d4612f3f565b6115dc612ee8565b90612db7565b30036116e75782156116d7576115f790613237565b8083116116bb575063ffffffff80600a5460a01c169081611642575b61105c8686611622878761396b565b80519161162e83612634565b825251918291602083526020830190612467565b633b9aca00918285029285840481036116a657038181116116935761105c97508461167b61162296959461168894611680941690612de3565b612daa565b600e546126aa565b600e55909138611613565b634e487b7160e01b875260118852602487fd5b601189634e487b7160e01b6000525260246000fd5b8560449184865192630b83ee4960e41b84528301526024820152fd5b8351634750846560e11b81528690fd5b835163016cda8f60e01b81526001600160a01b0390911681870190815230602082015281906040010390fd5b85516317140eff60e11b815233818a019081526001600160a01b0390921660208301529081906040010390fd5b5050346103cf57816003193601126103cf57517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b83346104915780600319360112610491576009546000906001600160a01b038116906117b1338314612cf1565b6001600160a01b0319166009557f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b5050346103cf5760203660031901126103cf576020906118036124de565b50517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152f35b5050346103cf57816003193601126103cf57602090600e549051908152f35b509134610491578160031936011261049157506105eb6020926118736124f4565b90339035613299565b5050346103cf57816003193601126103cf57600c5490516001600160a01b039091168152602090f35b50903461039d57602036600319011261039d578135906118d86118c6612f3f565b6118ce612ee8565b61167b8183612db7565b8083116119595750600e549283831161193e5750600d546001600160a01b031692611904908390612daa565b600e55611911828461396b565b519081527f1e151416f75a9fa58121e8ea2cf9c96559f5eaa9f2140705f1f9459cf7da68d260203392a380f35b91604493915192632da975dd60e01b84528301526024820152fd5b6044928492519263144337d560e11b84528301526024820152fd5b5050346103cf5760203660031901126103cf57907f5d55a9f17ebec95846f4d400ad862a51f9564a7973f6622d3c99a34feb6a0aec6020926119b46124de565b6009546001600160a01b0391906119ce9083163314612cf1565b16918291826001600160601b0360a01b600d541617600d55519380a28152f35b503461039d5760c036600319011261039d57803590611a0b6124f4565b9360643560ff81168091036103cf576001600160a01b038681169190338303611b76577f00000000000000000000000000000000000000000000000000000000000000001690813b15610aae5786519063d505accf60e01b825283868301523060248301528660448301526044356064830152608482015260843560a482015260a43560c4820152838160e48183865af18015611b6c57611b59575b508551636eb1769f60e11b81526001600160a01b03881685820190815230602082810191909152919283918290819060400103915afa928315610a4f5792611b26575b50838203611b00576020856105eb888088613299565b926084938551936387975ae160e01b855284015230602484015260448301526064820152fd5b9091506020813d8211611b51575b81611b4160209383612688565b8101031261048c57519038611aea565b3d9150611b34565b611b6590939193612620565b9138611aa7565b87513d86823e3d90fd5b86516358fe888560e01b8152338187019081526001600160a01b038a16602082015281906040010390fd5b50903461039d578260031936011261039d57600a546001600160a01b03929091838316919033839003611c14575050600954926001600160601b0360a01b938285821617600955167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08580a316600a5580f35b906020606492519162461bcd60e51b8352820152601f60248201527f4f776e61626c652f63616c6c65722d6e6f742d70656e64696e674f776e6572006044820152fd5b6124a7565b5050346103cf57806003193601126103cf57610f09602092611ca5611c7f6124de565b338352600186528483206001600160a01b038216845286529184902054602435906126aa565b90336126cd565b5050346103cf57816003193601126103cf57517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b5050346103cf57816003193601126103cf576020906105eb612a10565b509190346103cf57816003193601126103cf5780516370a0823160e01b815230848201526020939092906001600160a01b039085856024817f000000000000000000000000000000000000000000000000000000000000000086165afa948515611e74578395611e45575b508415611e37578351636e553f6560e01b81529081018581523060208201529091869183919082908690829060400103927f0000000000000000000000000000000000000000000000000000000000000000165af18015610d2257908591611e0e575b50505080518281527fab2246061d7b0dd3631d037e3f6da75782ae489eeb9f6af878a4b25df9b07c77843392a251908152f35b813d8311611e30575b611e218183612688565b81010312610491578381611ddb565b503d611e17565b835163a00207cf60e01b8152fd5b9094508581813d8311611e6d575b611e5d8183612688565b8101031261039d57519338611d78565b503d611e53565b84513d85823e3d90fd5b5050346103cf57816003193601126103cf576020905160ff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b50903461039d5760a036600319011261039d57611ed76124de565b926024359060ff8216809203610491576044359063ffffffff821680920361049157606435926001600160601b0384168094036103cf576001600160a01b0360843581811690819003610aae5781600b541680330361218e575081891691828552602099600f8b528886208b8a5191611f4f836125ee565b549160ff83161515938482528c868484019560ff8160081c161515875260101c16920194828652600014612181575090808760a48f8f8f968f978f92988f9951998a97889663b4db727f60e01b88528701526024860152604485015260648401528b6084840152620249f0f19182918a93612162575b5050611ff5578c8c610a188d611fd9612e03565b9051938493633a3514e760e01b85528401526024830190612467565b83909b999b5b16938415612152578a519b6311e7375f60e21b8d52878d888d82015260240152858d8b60448201526064015260848d015260a48c01528b8b847f000000000000000000000000000000000000000000000000000000000000000016818a5a9260c493f19a8b1561214857879b612115575b505161207c575b8a8a8a51908152f35b989698511690813b156121115760a49291859189519788968795635100dbf960e01b87528d870152602486015260448501528860648501526084840152620249f0f19081612102575b506120f35750610a18906120d7612e03565b9051938493637c65732960e11b85528401526024830190612467565b91503880808080808080612073565b61210b90612620565b386120c5565b8480fd5b909a508b81813d8311612141575b61212d8183612688565b8101031261213d5751993861206c565b8680fd5b503d612123565b8a513d89823e3d90fd5b8a5163e1c2596f60e01b81528a90fd5b612179929350803d10610a4857610a398183612688565b90388e611fc5565b90508491509b999b611ffb565b8751637f4b239760e11b815233818b019081526001600160a01b0390921660208301529081906040010390fd5b508290346103cf5760203660031901126103cf576121d76124de565b6009546001600160a01b0391906121f19083163314612cf1565b1690811561223d575080602093816001600160601b0360a01b600c541617600c5551927fb540015bf51edcbfd9e43df5316486615bf954f7b4c6cc0304eb3757f1601f95309180a38152f35b8351630ac5b1f760e11b8152fd5b5050346103cf5760603660031901126103cf57602090610f0961226c6124de565b6122746124f4565b604435916122838333836127cf565b613aa6565b5050346103cf57806003193601126103cf576020906122a56124de565b906122ae6124f4565b6001600160a01b03928316301492836122cc575b5050519015158152f35b600c548116911614915083806122c2565b5050346103cf57816003193601126103cf576020906105eb612f3f565b5050346103cf57816003193601126103cf57602090612317612f3f565b61231f612ee8565b10159051908152f35b5050346103cf57816003193601126103cf576020906105eb6131f9565b50913461049157602036600319011261049157506105eb602092612367612f3f565b61236f612ee8565b9135612f96565b5050346103cf57806003193601126103cf57602090610f096123966124de565b60243590336126cd565b5050346103cf57816003193601126103cf57805190826003546123c2816125b4565b808552916001918083169081156110be57506001146123ed5750505061104a8261105c940383612688565b9450600385527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b8286106124325750505061104a82602061105c9582010194611038565b80546020878701810191909152909501948101612415565b5050346103cf57816003193601126103cf576020906105eb612ee8565b919082519283825260005b848110612493575050826000602080949584010152601f8019910116010190565b602081830181015184830182015201612472565b3461048c57602036600319011261048c5760206124d66124c5612f3f565b6124cd612ee8565b90600435613120565b604051908152f35b600435906001600160a01b038216820361048c57565b602435906001600160a01b038216820361048c57565b3461048c57602036600319011261048c576125236124de565b50602061252e612f3f565b80612537612ee8565b600092911161254a576124d6915061314d565b506124d6565b606090600319011261048c57600435906001600160a01b0390602435828116810361048c5791604435908116810361048c5790565b3461048c57602036600319011261048c5760206124d66125a3612f3f565b6125ab612ee8565b90600435612fd2565b90600182811c921680156125e4575b60208310146125ce57565b634e487b7160e01b600052602260045260246000fd5b91607f16916125c3565b6060810190811067ffffffffffffffff82111761260a57604052565b634e487b7160e01b600052604160045260246000fd5b67ffffffffffffffff811161260a57604052565b6020810190811067ffffffffffffffff82111761260a57604052565b60a0810190811067ffffffffffffffff82111761260a57604052565b6040810190811067ffffffffffffffff82111761260a57604052565b90601f8019910116810190811067ffffffffffffffff82111761260a57604052565b919082018092116126b757565b634e487b7160e01b600052601160045260246000fd5b6001600160a01b0390811691821561277e571691821561272e5760207f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925918360005260018252604060002085600052825280604060002055604051908152a3565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b60405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b9060018060a01b0380831660005260016020526040600020908216600052602052604060002054926000198403612807575b50505050565b808410612822576128199303916126cd565b38808080612801565b60405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606490fd5b600581101561296b57806128785750565b600181036128c55760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606490fd5b600281036129125760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606490fd5b60031461291b57565b60405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608490fd5b634e487b7160e01b600052602160045260246000fd5b9291907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311612a045791608094939160ff602094604051948552168484015260408301526060820152600093849182805260015afa156129f75781516001600160a01b038116156129f1579190565b50600190565b50604051903d90823e3d90fd5b50505050600090600390565b307f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161480612b12575b15612a6b577f000000000000000000000000000000000000000000000000000000000000000090565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f000000000000000000000000000000000000000000000000000000000000000060408201527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260a0815260c0810181811067ffffffffffffffff82111761260a5760405251902090565b507f00000000000000000000000000000000000000000000000000000000000000004614612a42565b60ff8114612b795760ff811690601f8211612b675760405191612b5d8361266c565b8252602082015290565b604051632cd44ac360e21b8152600490fd5b50604051600554816000612b8c836125b4565b80835292600190818116908115612c155750600114612bb6575b50612bb392500382612688565b90565b6005600090815291507f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db05b848310612bfa5750612bb3935050810160200138612ba6565b81935090816020925483858901015201910190918492612be1565b905060209250612bb394915060ff191682840152151560051b82010138612ba6565b60ff8114612c595760ff811690601f8211612b675760405191612b5d8361266c565b50604051600654816000612c6c836125b4565b80835292600190818116908115612c155750600114612c925750612bb392500382612688565b6006600090815291507ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f5b848310612cd65750612bb3935050810160200138612ba6565b81935090816020925483858901015201910190918492612cbd565b15612cf857565b60405162461bcd60e51b815260206004820152601860248201527f4f776e61626c652f63616c6c65722d6e6f742d6f776e657200000000000000006044820152606490fd5b9081602091031261048c57516001600160a01b038116810361048c5790565b612d646131f9565b80151580612d96575b612d775750600090565b612d92633b9aca009163ffffffff600a5460a01c1690612dd0565b0490565b5063ffffffff600a5460a01c161515612d6d565b919082039182116126b757565b11612dbe57565b60405163414db2e160e01b8152600490fd5b818102929181159184041417156126b757565b8115612ded570490565b634e487b7160e01b600052601260045260246000fd5b3d15612e3e573d9067ffffffffffffffff821161260a5760405191612e32601f8201601f191660200184612688565b82523d6000602084013e565b606090565b604051633de222bb60e21b81523060048201526001600160a01b039091166024820152602081806044810103817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115612edc57600091612eae575090565b906020823d8211612ed4575b81612ec760209383612688565b8101031261049157505190565b3d9150612eba565b6040513d6000823e3d90fd5b60405163ce96cb7760e01b81523060048201526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115612edc57600091612eae575090565b6040516339370aa960e21b81523060048201526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115612edc57600091612eae575090565b9182158015612fca575b612fc557612fae9082613b56565b9081612fbc57505050600090565b612bb392613009565b505090565b508115612fa0565b9182158015613001575b612fc557612fea9082613b56565b9081612ff857505050600090565b612bb392613033565b508115612fdc565b9190613016828285613033565b928215612ded57096130255790565b600181018091116126b75790565b9160001982840992828102928380861095039480860395146130e657848311156130a9578291096001821901821680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b60405162461bcd60e51b81526020600482015260156024820152744d6174683a206d756c446976206f766572666c6f7760581b6044820152606490fd5b505090612bb39250612de3565b9182158015613118575b612fc55761310b9082613b56565b80612fbc57505050600090565b5081156130fd565b9182158015613145575b612fc5576131389082613b56565b80612ff857505050600090565b50811561312a565b6001600160601b039081039081116126b75760405163402d267d60e01b8152306004820152906020826024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa918215612edc576000926131c6575b50808210156131c1575090565b905090565b90916020823d82116131f1575b816131e060209383612688565b8101031261049157505190386131b4565b3d91506131d3565b613201612f3f565b61321f61320c612ee8565b809261321a600e54826126aa565b6130f3565b8181111561322e575050600090565b612bb391612daa565b306001600160a01b0382160361327057506132506131f9565b633b9aca0061326a63ffffffff600a5460a01c1683612dd0565b04900390565b60405163016cda8f60e01b81526001600160a01b03919091166004820152306024820152604490fd5b916000906132a5612f3f565b6132b0611117612ee8565b6132b98161314d565b851161356f5750831561355d57604080516370a0823160e01b81523060048201526020936001600160a01b03917f000000000000000000000000000000000000000000000000000000000000000083168682602481845afa918215613553578392613524575b508189116133f4575b50508251636e553f6560e01b815260048101889052306024820152908582604481847f000000000000000000000000000000000000000000000000000000000000000088165af19081156133e957509085916133c0575b505080836133ae887fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d79661396b565b8784519681885287015216941692a390565b813d83116133e2575b6133d38183612688565b8101031261048c57833861337f565b503d6133c9565b8451903d90823e3d90fd5b61347e9183908061351a575b50801561351257905b83808751938a8501906323b872dd60e01b8252888d16602487015230604487015260648601526064855261343c85612650565b8851946134488661266c565b8b86527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648c870152519082855af16112f3612e03565b80518681159182156134f2575b505090501561349b573880613328565b825162461bcd60e51b815260048101869052602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608490fd5b83809293500103126103cf5785015180151581036103cf5780863861348b565b508890613409565b9050890338613400565b9091508681813d831161354c575b61353c8183612688565b8101031261048c5751903861331f565b503d613532565b85513d85823e3d90fd5b60405163b31accb760e01b8152600490fd5b61357e610a189186945061314d565b604051632f0b561760e21b81526001600160a01b039093166004840152602483019390935260448201929092529081906064820190565b9192901561361757508151156135c9575090565b3b156135d25790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b82519091501561362a5750805190602001fd5b60405162461bcd60e51b815260206004820152908190610a18906024830190612467565b93946001600160a01b03808416959194818316949391926000908289880361395a575b50508087156138b4575b847f0000000000000000000000000000000000000000000000000000000000000000166136a784613a3e565b90803b1561039d57604080516346f9647360e11b81526001600160a01b0390991660048a01526001600160601b039092166024890152909690829082908183816044810103925af180156138aa5761389b575b5090855197838952828a600080516020613b638339815191526020809ca3156137f757508451632d182be560e21b8152600481018a90526001600160a01b0384166024820152306044820152908782606481847f00000000000000000000000000000000000000000000000000000000000000008a165af1908115610a4f57509087916137ce575b50505b87156137bd5783518881529586015216927ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db9190a490565b835163f3c41a2b60e01b8152600490fd5b813d83116137f0575b6137e18183612688565b8101031261048c578538613782565b503d6137d7565b8551635d043b2960e11b815260048101919091526001600160a01b0384166024820152306044820152919850908681606481857f000000000000000000000000000000000000000000000000000000000000000089165af19182156138905791613863575b5096613785565b90508581813d8311613889575b61387a8183612688565b8101031261048c57513861385c565b503d613870565b8551903d90823e3d90fd5b6138a490612620565b386136fa565b87513d84823e3d90fd5b604051636c82bbbf60e11b81523060048201529091506020816024817f000000000000000000000000000000000000000000000000000000000000000089165afa801561394f57829061391c575b613916915061390f612f3f565b9084613033565b9061367b565b506020813d8211613947575b8161393560209383612688565b810103126103cf576139169051613902565b3d9150613928565b6040513d84823e3d90fd5b61396491876127cf565b3882613671565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116916139a084613a3e565b833b1561048c57604051626c096960e61b81526001600160a01b03831660048201526001600160601b0391909116602482015260009384908290604490829084905af18015613a3357613a0d575b50600080516020613b63833981519152916020916040519586521693a3565b9160209193613a2a600080516020613b6383398151915294612620565b939150916139ee565b6040513d86823e3d90fd5b6001600160601b0390818111613a52571690565b60405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203960448201526536206269747360d01b6064820152608490fd5b916001600160a01b03907f00000000000000000000000000000000000000000000000000000000000000008216613adc82613a3e565b94813b1561048c5760648491600080946001600160601b03604051988996879563c661667d60e01b8752169a8b6004870152169a8b60248601521660448401525af1908115612edc57600080516020613b6383398151915292602092613b47575b50604051908152a3565b613b5090612620565b38613b3d565b808210156131c157509056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa264697066735822122051df9205aef21eda3cc91d0ccc148b45a8c6f88eaf5720eb4d9e283529a9f7a964736f6c634300081300330000000000000000000000000b2c639c533813f4aa9d7837caf62653d097ff85000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001600000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c6000000000000000000000000e32e5e1c5f0c80bd26def2d0ea5008c107000d6a000000000000000000000000dc6ab38f9590cb8e4357e0a391689a7c5ef7681e00000000000000000000000013a751fafd4214cfc1f95f7b027ef432965312c4000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013a751fafd4214cfc1f95f7b027ef432965312c400000000000000000000000000000000000000000000000000000000000000115072697a652055534443202d204161766500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000057055534443000000000000000000000000000000000000000000000000000000
Deployed Bytecode
0x6040608081526004908136101561001557600080fd5b600091823560e01c806301e1d1141461244a57806306fdde03146123a057806307a2d13a14611c57578063095ea7b3146123765780630a28a477146123455780630d1e5255146123285780630f2630e8146122fa57806318160ddd146122dd5780631b5719241461228857806323b872dd1461224b57806325fa66e0146121bb5780632895cace14611ebc578063313ce56714611e7e57806335faa41614611d0d5780633644e51514611cf057806338d52e0f14611cac5780633950935114611c5c578063402d267d14610b755780634cdad50614611c575780634e71e0c814611ba157806350921b23146119ee57806363003b161461197457806363e4db75146118a5578063649f23941461187c5780636e553f65146118525780636f711fb214611833578063700f04ef146117e557806370a08231146105c5578063715018a614611784578063719ce73e146117405780637cc99d3f1461157e5780637ecebe001461154657806384b0196e146114515780638da5cb5b1461142857806394bf804d146110e657806395d89b4114610ffa578063a457c2d714610f54578063a7f8a5e214610f10578063a9059cbb14610edf578063b0812d7b14610e9b578063b0fcf62614610e75578063b3d7f6b914610e44578063b460af9414610d70578063b5a7efe514610d53578063b6cce5e214610c0b578063ba08765214610b7a578063c63d75b614610b75578063c6e6f592146103a1578063c78c72c114610ab6578063c8576e611461089a578063cdfb58321461080c578063ce96cb77146107d2578063d379be23146107a9578063d505accf146105f2578063d905777e146105c5578063dd62ed3e14610577578063de03f408146104e5578063e16777c1146104bd578063e30c397814610494578063e4e243ac146103d3578063edb8eb80146103a6578063ef8b30f7146103a15763f2fde38b146102d657600080fd5b3461039d57602036600319011261039d576102ef6124de565b6009546001600160a01b0391906103099083163314612cf1565b1691821561034c575050600a80546001600160a01b031916821790557f239a2ddded15777fa246aed5f7e1a9bc69a39d4eb4a397034d1d85766cca7d4c8280a280f35b906020608492519162461bcd60e51b8352820152602560248201527f4f776e61626c652f70656e64696e674f776e65722d6e6f742d7a65726f2d6164604482015264647265737360d81b6064820152fd5b8280fd5b612585565b5050346103cf57816003193601126103cf57600d5490516001600160a01b039091168152602090f35b5080fd5b5082346104915760203660031901126104915750803563ffffffff81169182820361048c5761040d60018060a01b03600954163314612cf1565b633b9aca008084101561047057600a805463ffffffff60a01b191660a085901b63ffffffff60a01b161790558451848152602090859087907fefb99600b8c2baadc10ee4fe77c625b379acb4c29fbb0b90a5f17652d7de0341908490a151908152f35b91509160449351926338747b7960e21b84528301526024820152fd5b600080fd5b80fd5b5050346103cf57816003193601126103cf57600a5490516001600160a01b039091168152602090f35b5050346103cf57816003193601126103cf5760209063ffffffff600a5460a01c169051908152f35b5050346103cf5760203660031901126103cf5790816060926105056124de565b9280828051610513816125ee565b828152826020820152015260018060a01b038094168152600f602052209181519261053d846125ee565b5460ff81161515938481528284602083019260ff8560081c1615158452019260101c16825283519485525115156020850152511690820152f35b5050346103cf57806003193601126103cf576020916105946124de565b8261059d6124f4565b6001600160a01b03928316845260018652922091166000908152908352819020549051908152f35b5050346103cf5760203660031901126103cf576020906105eb6105e66124de565b612e43565b9051908152f35b508290346103cf5760e03660031901126103cf5761060e6124de565b6106166124f4565b906044359260643560843560ff8116810361048c578142116107665760018060a01b0390818516928389526007602052898920908154916001830190558a519060208201927f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98452868d840152858a1660608401528a608084015260a083015260c082015260c0815260e0810181811067ffffffffffffffff821117610751578b525190206106f9916106f1916106cb612a10565b908c519161190160f01b83526002830152602282015260c43591604260a4359220612981565b919091612867565b160361070e575061070b9394506126cd565b80f35b606490602087519162461bcd60e51b8352820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152fd5b604187634e487b7160e01b6000525260246000fd5b875162461bcd60e51b8152602081850152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606490fd5b5050346103cf57816003193601126103cf57600b5490516001600160a01b039091168152602090f35b5050346103cf5760203660031901126103cf576020906105eb6107f66105e66124de565b6107fe612f3f565b610806612ee8565b91613120565b508290346103cf5760203660031901126103cf576108286124de565b6009546001600160a01b0391906108429083163314612cf1565b1690811561088c5750807fa04eca05f1c4f5674beaad80f345070124aa2192abced410b9b227c0c04e755a602094826001600160601b0360a01b600b541617600b55519380a28152f35b8351634d9808e160e11b8152fd5b50903461039d57606036600319011261039d576108b56124de565b9160443567ffffffffffffffff808211610ab25736602383011215610ab25781830135908111610ab25736910160240111610aae57600c546001600160a01b039190821633819003610a815750817f000000000000000000000000e32e5e1c5f0c80bd26def2d0ea5008c107000d6a1691835194636877812560e11b80875260209687818681895afa908115610a77579084918a91610a5a575b5016838316036109c4575050508291604485928795519586938492630eedfb4560e41b8452309084015260243560248401525af19081156109bb5750610993578280f35b813d83116109b4575b6109a68183612688565b8101031261048c5738808280f35b503d61099c565b513d85823e3d90fd5b958088959293978588518095819382525afa948515610a4f5794610a1c575b50509251630c0760c160e21b81526001600160a01b039384169181019182529390911691909116602082015281906040010390fd5b0390fd5b610a1894509081610a4192903d10610a48575b610a398183612688565b810190612d3d565b92866109e3565b503d610a2f565b8651903d90823e3d90fd5b610a719150893d8b11610a4857610a398183612688565b3861094f565b87513d8b823e3d90fd5b83516317140eff60e11b8152339281019283526001600160a01b0390911660208301529081906040010390fd5b8380fd5b8580fd5b50903461039d57606036600319011261039d57338352600f60205280832091359081151580920361048c5782549060243580151580910361048c57604435946001600160a01b03861693848703610b715760609662010000600160b01b039060101b169060ff87169069ffffffffffffffffffff60b01b161761ff008460081b16171790558151938452602084015282015220337f5eaf51436f308830fc57b00bb6843675b383bce9b2c669e1b9ce60de8bbb9e8e8380a380f35b8780fd5b61250a565b5091346104915750610b8b36612550565b93610b9885939293612e43565b8211610bcd5750926105eb91602094610baf612f3f565b92610bc6610bbb612ee8565b858110159584613120565b923361364e565b610a18848693610bdc85612e43565b9151636c6e33c560e01b81526001600160a01b0390951693850193845260208401526040830152829160600190565b50903461039d576020928360031936011261049157823592610c2e333386613299565b5082516316bef07560e31b8152308282019081523360208201526001600160a01b037f000000000000000000000000499a9f249ec4c8ea190bebbfd96f9a83bf4f6e528116939290918890829081906040010381875afa908115610d495790600192918691610d2c575b501603610cd8575b505050805182815282848201527f64939930c3fd0a1fe9e7fb9810272db7730a0f02b900972787bcb79fb6fd3d2d823392a251908152f35b813b1561039d578291602483928651948593849263766c4f3760e01b845233908401525af18015610d2257610d0e575b80610ca0565b610d188291612620565b6104915780610d08565b83513d84823e3d90fd5b610d439150893d8b11610a4857610a398183612688565b38610c98565b86513d87823e3d90fd5b5050346103cf57816003193601126103cf576020906105eb612d5c565b508290346103cf57610d8136612550565b9390610d8f6107f686612e43565b8311610e02579082610dc392610da3612f3f565b610dab612ee8565b81811080159550610df0575050819687915b3361364e565b90808210610dd5576020848651908152f35b845163a253e87960e01b815292830152602482015260449150fd5b610dfa9184612f96565b968791610dbd565b505083610a1891610e156107f686612e43565b91516390bb24b560e01b81526001600160a01b0390951693850193845260208401526040830152829160600190565b50913461049157602036600319011261049157506105eb602092610e66612f3f565b610e6e612ee8565b91356130f3565b5050346103cf5760203660031901126103cf576020906105eb610e966124de565b613237565b5050346103cf57816003193601126103cf57517f000000000000000000000000499a9f249ec4c8ea190bebbfd96f9a83bf4f6e526001600160a01b03168152602090f35b5050346103cf57806003193601126103cf57602090610f09610eff6124de565b6024359033613aa6565b5160018152f35b5050346103cf57816003193601126103cf57517f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c66001600160a01b03168152602090f35b508234610491578260031936011261049157610f6e6124de565b91836024359233815260016020522060018060a01b038416600052602052836000205490828210610fa957602085610f0985850387336126cd565b608490602086519162461bcd60e51b8352820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152fd5b50913461049157806003193601126104915750805190600092805461101e816125b4565b808552916001918083169081156110be5750600114611060575b50505061104a8261105c940383612688565b51918291602083526020830190612467565b0390f35b600090815294507f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b8286106110a65750505061104a82602061105c9582010194611038565b80546020878701810191909152909501948101611089565b61105c97508693506020925061104a94915060ff191682840152151560051b82010194611038565b509134610491578160031936011261049157508135906111046124f4565b61110c612f3f565b61111d611117612ee8565b82612db7565b6111268161314d565b84116113ea575082156113da5781516370a0823160e01b815230818601526020946001600160a01b03917f0000000000000000000000000b2c639c533813f4aa9d7837caf62653d097ff858316908781602481855afa9081156113cf579088929160009161139f575b50808811611268575b50508451636e553f6560e01b81529182018681523060208201528290819060400103816000867f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c6165af1801561125d57908691611234575b50506111fc848361396b565b825191848352848684015216907fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7833392a351908152f35b813d8311611256575b6112478183612688565b8101031261048c5784386111f0565b503d61123d565b84513d6000823e3d90fd5b6112f9925060009080611395575b50801561138d57905b6000808851938b8501906323b872dd60e01b82523360248701523060448701526064860152606485526112b185612650565b8951946112bd8661266c565b8c86527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648d870152519082855af16112f3612e03565b916135b5565b805187811591821561136d575b505090501561131757853880611198565b835162461bcd60e51b8152908101869052602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608490fd5b838092935001031261048c57860151801515810361048c57808738611306565b50869061127f565b9050870338611276565b919282813d83116113c8575b6113b58183612688565b810103126104915750908791513861118f565b503d6113ab565b86513d6000823e3d90fd5b815163b31accb760e01b81528490fd5b610a1883856113f9889461314d565b9151634acfb82760e11b81526001600160a01b0390951693850193845260208401526040830152829160600190565b5050346103cf57816003193601126103cf5760095490516001600160a01b039091168152602090f35b5050346103cf57816003193601126103cf579061148d7f5072697a652055534443202d2041617665000000000000000000000000000011612b3b565b6114b67f3100000000000000000000000000000000000000000000000000000000000001612c37565b918351916114c383612634565b8183526114f88551958695600f60f81b87526114eb60209460e0868a015260e0890190612467565b9187830390880152612467565b904660608601523060808601528260a086015284820360c08601528080855193848152019401925b82811061152f57505050500390f35b835185528695509381019392810192600101611520565b5050346103cf5760203660031901126103cf5760209181906001600160a01b0361156e6124de565b1681526007845220549051908152f35b509190346103cf5760803660031901126103cf5761159a6124de565b506115a36124f4565b6001600160a01b039060443582811680820361048c5760643593600c541680330361171357506115e26115d4612f3f565b6115dc612ee8565b90612db7565b30036116e75782156116d7576115f790613237565b8083116116bb575063ffffffff80600a5460a01c169081611642575b61105c8686611622878761396b565b80519161162e83612634565b825251918291602083526020830190612467565b633b9aca00918285029285840481036116a657038181116116935761105c97508461167b61162296959461168894611680941690612de3565b612daa565b600e546126aa565b600e55909138611613565b634e487b7160e01b875260118852602487fd5b601189634e487b7160e01b6000525260246000fd5b8560449184865192630b83ee4960e41b84528301526024820152fd5b8351634750846560e11b81528690fd5b835163016cda8f60e01b81526001600160a01b0390911681870190815230602082015281906040010390fd5b85516317140eff60e11b815233818a019081526001600160a01b0390921660208301529081906040010390fd5b5050346103cf57816003193601126103cf57517f000000000000000000000000e32e5e1c5f0c80bd26def2d0ea5008c107000d6a6001600160a01b03168152602090f35b83346104915780600319360112610491576009546000906001600160a01b038116906117b1338314612cf1565b6001600160a01b0319166009557f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b5050346103cf5760203660031901126103cf576020906118036124de565b50517f000000000000000000000000e32e5e1c5f0c80bd26def2d0ea5008c107000d6a6001600160a01b03168152f35b5050346103cf57816003193601126103cf57602090600e549051908152f35b509134610491578160031936011261049157506105eb6020926118736124f4565b90339035613299565b5050346103cf57816003193601126103cf57600c5490516001600160a01b039091168152602090f35b50903461039d57602036600319011261039d578135906118d86118c6612f3f565b6118ce612ee8565b61167b8183612db7565b8083116119595750600e549283831161193e5750600d546001600160a01b031692611904908390612daa565b600e55611911828461396b565b519081527f1e151416f75a9fa58121e8ea2cf9c96559f5eaa9f2140705f1f9459cf7da68d260203392a380f35b91604493915192632da975dd60e01b84528301526024820152fd5b6044928492519263144337d560e11b84528301526024820152fd5b5050346103cf5760203660031901126103cf57907f5d55a9f17ebec95846f4d400ad862a51f9564a7973f6622d3c99a34feb6a0aec6020926119b46124de565b6009546001600160a01b0391906119ce9083163314612cf1565b16918291826001600160601b0360a01b600d541617600d55519380a28152f35b503461039d5760c036600319011261039d57803590611a0b6124f4565b9360643560ff81168091036103cf576001600160a01b038681169190338303611b76577f0000000000000000000000000b2c639c533813f4aa9d7837caf62653d097ff851690813b15610aae5786519063d505accf60e01b825283868301523060248301528660448301526044356064830152608482015260843560a482015260a43560c4820152838160e48183865af18015611b6c57611b59575b508551636eb1769f60e11b81526001600160a01b03881685820190815230602082810191909152919283918290819060400103915afa928315610a4f5792611b26575b50838203611b00576020856105eb888088613299565b926084938551936387975ae160e01b855284015230602484015260448301526064820152fd5b9091506020813d8211611b51575b81611b4160209383612688565b8101031261048c57519038611aea565b3d9150611b34565b611b6590939193612620565b9138611aa7565b87513d86823e3d90fd5b86516358fe888560e01b8152338187019081526001600160a01b038a16602082015281906040010390fd5b50903461039d578260031936011261039d57600a546001600160a01b03929091838316919033839003611c14575050600954926001600160601b0360a01b938285821617600955167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08580a316600a5580f35b906020606492519162461bcd60e51b8352820152601f60248201527f4f776e61626c652f63616c6c65722d6e6f742d70656e64696e674f776e6572006044820152fd5b6124a7565b5050346103cf57806003193601126103cf57610f09602092611ca5611c7f6124de565b338352600186528483206001600160a01b038216845286529184902054602435906126aa565b90336126cd565b5050346103cf57816003193601126103cf57517f0000000000000000000000000b2c639c533813f4aa9d7837caf62653d097ff856001600160a01b03168152602090f35b5050346103cf57816003193601126103cf576020906105eb612a10565b509190346103cf57816003193601126103cf5780516370a0823160e01b815230848201526020939092906001600160a01b039085856024817f0000000000000000000000000b2c639c533813f4aa9d7837caf62653d097ff8586165afa948515611e74578395611e45575b508415611e37578351636e553f6560e01b81529081018581523060208201529091869183919082908690829060400103927f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c6165af18015610d2257908591611e0e575b50505080518281527fab2246061d7b0dd3631d037e3f6da75782ae489eeb9f6af878a4b25df9b07c77843392a251908152f35b813d8311611e30575b611e218183612688565b81010312610491578381611ddb565b503d611e17565b835163a00207cf60e01b8152fd5b9094508581813d8311611e6d575b611e5d8183612688565b8101031261039d57519338611d78565b503d611e53565b84513d85823e3d90fd5b5050346103cf57816003193601126103cf576020905160ff7f0000000000000000000000000000000000000000000000000000000000000006168152f35b50903461039d5760a036600319011261039d57611ed76124de565b926024359060ff8216809203610491576044359063ffffffff821680920361049157606435926001600160601b0384168094036103cf576001600160a01b0360843581811690819003610aae5781600b541680330361218e575081891691828552602099600f8b528886208b8a5191611f4f836125ee565b549160ff83161515938482528c868484019560ff8160081c161515875260101c16920194828652600014612181575090808760a48f8f8f968f978f92988f9951998a97889663b4db727f60e01b88528701526024860152604485015260648401528b6084840152620249f0f19182918a93612162575b5050611ff5578c8c610a188d611fd9612e03565b9051938493633a3514e760e01b85528401526024830190612467565b83909b999b5b16938415612152578a519b6311e7375f60e21b8d52878d888d82015260240152858d8b60448201526064015260848d015260a48c01528b8b847f000000000000000000000000e32e5e1c5f0c80bd26def2d0ea5008c107000d6a16818a5a9260c493f19a8b1561214857879b612115575b505161207c575b8a8a8a51908152f35b989698511690813b156121115760a49291859189519788968795635100dbf960e01b87528d870152602486015260448501528860648501526084840152620249f0f19081612102575b506120f35750610a18906120d7612e03565b9051938493637c65732960e11b85528401526024830190612467565b91503880808080808080612073565b61210b90612620565b386120c5565b8480fd5b909a508b81813d8311612141575b61212d8183612688565b8101031261213d5751993861206c565b8680fd5b503d612123565b8a513d89823e3d90fd5b8a5163e1c2596f60e01b81528a90fd5b612179929350803d10610a4857610a398183612688565b90388e611fc5565b90508491509b999b611ffb565b8751637f4b239760e11b815233818b019081526001600160a01b0390921660208301529081906040010390fd5b508290346103cf5760203660031901126103cf576121d76124de565b6009546001600160a01b0391906121f19083163314612cf1565b1690811561223d575080602093816001600160601b0360a01b600c541617600c5551927fb540015bf51edcbfd9e43df5316486615bf954f7b4c6cc0304eb3757f1601f95309180a38152f35b8351630ac5b1f760e11b8152fd5b5050346103cf5760603660031901126103cf57602090610f0961226c6124de565b6122746124f4565b604435916122838333836127cf565b613aa6565b5050346103cf57806003193601126103cf576020906122a56124de565b906122ae6124f4565b6001600160a01b03928316301492836122cc575b5050519015158152f35b600c548116911614915083806122c2565b5050346103cf57816003193601126103cf576020906105eb612f3f565b5050346103cf57816003193601126103cf57602090612317612f3f565b61231f612ee8565b10159051908152f35b5050346103cf57816003193601126103cf576020906105eb6131f9565b50913461049157602036600319011261049157506105eb602092612367612f3f565b61236f612ee8565b9135612f96565b5050346103cf57806003193601126103cf57602090610f096123966124de565b60243590336126cd565b5050346103cf57816003193601126103cf57805190826003546123c2816125b4565b808552916001918083169081156110be57506001146123ed5750505061104a8261105c940383612688565b9450600385527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b8286106124325750505061104a82602061105c9582010194611038565b80546020878701810191909152909501948101612415565b5050346103cf57816003193601126103cf576020906105eb612ee8565b919082519283825260005b848110612493575050826000602080949584010152601f8019910116010190565b602081830181015184830182015201612472565b3461048c57602036600319011261048c5760206124d66124c5612f3f565b6124cd612ee8565b90600435613120565b604051908152f35b600435906001600160a01b038216820361048c57565b602435906001600160a01b038216820361048c57565b3461048c57602036600319011261048c576125236124de565b50602061252e612f3f565b80612537612ee8565b600092911161254a576124d6915061314d565b506124d6565b606090600319011261048c57600435906001600160a01b0390602435828116810361048c5791604435908116810361048c5790565b3461048c57602036600319011261048c5760206124d66125a3612f3f565b6125ab612ee8565b90600435612fd2565b90600182811c921680156125e4575b60208310146125ce57565b634e487b7160e01b600052602260045260246000fd5b91607f16916125c3565b6060810190811067ffffffffffffffff82111761260a57604052565b634e487b7160e01b600052604160045260246000fd5b67ffffffffffffffff811161260a57604052565b6020810190811067ffffffffffffffff82111761260a57604052565b60a0810190811067ffffffffffffffff82111761260a57604052565b6040810190811067ffffffffffffffff82111761260a57604052565b90601f8019910116810190811067ffffffffffffffff82111761260a57604052565b919082018092116126b757565b634e487b7160e01b600052601160045260246000fd5b6001600160a01b0390811691821561277e571691821561272e5760207f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925918360005260018252604060002085600052825280604060002055604051908152a3565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b60405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b9060018060a01b0380831660005260016020526040600020908216600052602052604060002054926000198403612807575b50505050565b808410612822576128199303916126cd565b38808080612801565b60405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606490fd5b600581101561296b57806128785750565b600181036128c55760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606490fd5b600281036129125760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606490fd5b60031461291b57565b60405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608490fd5b634e487b7160e01b600052602160045260246000fd5b9291907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311612a045791608094939160ff602094604051948552168484015260408301526060820152600093849182805260015afa156129f75781516001600160a01b038116156129f1579190565b50600190565b50604051903d90823e3d90fd5b50505050600090600390565b307f00000000000000000000000077935f2c72b5eb814753a05921ae495aa283906b6001600160a01b03161480612b12575b15612a6b577f61f83d51e6b100824990699058ca11cb9fa56fb0ba6ed17d9adbac28b2f5218190565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f6794896e0da3e20040b53d0910b39d7fb9c24ced58f829469985a057455f1c7760408201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260a0815260c0810181811067ffffffffffffffff82111761260a5760405251902090565b507f000000000000000000000000000000000000000000000000000000000000000a4614612a42565b60ff8114612b795760ff811690601f8211612b675760405191612b5d8361266c565b8252602082015290565b604051632cd44ac360e21b8152600490fd5b50604051600554816000612b8c836125b4565b80835292600190818116908115612c155750600114612bb6575b50612bb392500382612688565b90565b6005600090815291507f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db05b848310612bfa5750612bb3935050810160200138612ba6565b81935090816020925483858901015201910190918492612be1565b905060209250612bb394915060ff191682840152151560051b82010138612ba6565b60ff8114612c595760ff811690601f8211612b675760405191612b5d8361266c565b50604051600654816000612c6c836125b4565b80835292600190818116908115612c155750600114612c925750612bb392500382612688565b6006600090815291507ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f5b848310612cd65750612bb3935050810160200138612ba6565b81935090816020925483858901015201910190918492612cbd565b15612cf857565b60405162461bcd60e51b815260206004820152601860248201527f4f776e61626c652f63616c6c65722d6e6f742d6f776e657200000000000000006044820152606490fd5b9081602091031261048c57516001600160a01b038116810361048c5790565b612d646131f9565b80151580612d96575b612d775750600090565b612d92633b9aca009163ffffffff600a5460a01c1690612dd0565b0490565b5063ffffffff600a5460a01c161515612d6d565b919082039182116126b757565b11612dbe57565b60405163414db2e160e01b8152600490fd5b818102929181159184041417156126b757565b8115612ded570490565b634e487b7160e01b600052601260045260246000fd5b3d15612e3e573d9067ffffffffffffffff821161260a5760405191612e32601f8201601f191660200184612688565b82523d6000602084013e565b606090565b604051633de222bb60e21b81523060048201526001600160a01b039091166024820152602081806044810103817f000000000000000000000000499a9f249ec4c8ea190bebbfd96f9a83bf4f6e526001600160a01b03165afa908115612edc57600091612eae575090565b906020823d8211612ed4575b81612ec760209383612688565b8101031261049157505190565b3d9150612eba565b6040513d6000823e3d90fd5b60405163ce96cb7760e01b81523060048201526020816024817f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c66001600160a01b03165afa908115612edc57600091612eae575090565b6040516339370aa960e21b81523060048201526020816024817f000000000000000000000000499a9f249ec4c8ea190bebbfd96f9a83bf4f6e526001600160a01b03165afa908115612edc57600091612eae575090565b9182158015612fca575b612fc557612fae9082613b56565b9081612fbc57505050600090565b612bb392613009565b505090565b508115612fa0565b9182158015613001575b612fc557612fea9082613b56565b9081612ff857505050600090565b612bb392613033565b508115612fdc565b9190613016828285613033565b928215612ded57096130255790565b600181018091116126b75790565b9160001982840992828102928380861095039480860395146130e657848311156130a9578291096001821901821680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b60405162461bcd60e51b81526020600482015260156024820152744d6174683a206d756c446976206f766572666c6f7760581b6044820152606490fd5b505090612bb39250612de3565b9182158015613118575b612fc55761310b9082613b56565b80612fbc57505050600090565b5081156130fd565b9182158015613145575b612fc5576131389082613b56565b80612ff857505050600090565b50811561312a565b6001600160601b039081039081116126b75760405163402d267d60e01b8152306004820152906020826024817f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c66001600160a01b03165afa918215612edc576000926131c6575b50808210156131c1575090565b905090565b90916020823d82116131f1575b816131e060209383612688565b8101031261049157505190386131b4565b3d91506131d3565b613201612f3f565b61321f61320c612ee8565b809261321a600e54826126aa565b6130f3565b8181111561322e575050600090565b612bb391612daa565b306001600160a01b0382160361327057506132506131f9565b633b9aca0061326a63ffffffff600a5460a01c1683612dd0565b04900390565b60405163016cda8f60e01b81526001600160a01b03919091166004820152306024820152604490fd5b916000906132a5612f3f565b6132b0611117612ee8565b6132b98161314d565b851161356f5750831561355d57604080516370a0823160e01b81523060048201526020936001600160a01b03917f0000000000000000000000000b2c639c533813f4aa9d7837caf62653d097ff8583168682602481845afa918215613553578392613524575b508189116133f4575b50508251636e553f6560e01b815260048101889052306024820152908582604481847f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c688165af19081156133e957509085916133c0575b505080836133ae887fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d79661396b565b8784519681885287015216941692a390565b813d83116133e2575b6133d38183612688565b8101031261048c57833861337f565b503d6133c9565b8451903d90823e3d90fd5b61347e9183908061351a575b50801561351257905b83808751938a8501906323b872dd60e01b8252888d16602487015230604487015260648601526064855261343c85612650565b8851946134488661266c565b8b86527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648c870152519082855af16112f3612e03565b80518681159182156134f2575b505090501561349b573880613328565b825162461bcd60e51b815260048101869052602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608490fd5b83809293500103126103cf5785015180151581036103cf5780863861348b565b508890613409565b9050890338613400565b9091508681813d831161354c575b61353c8183612688565b8101031261048c5751903861331f565b503d613532565b85513d85823e3d90fd5b60405163b31accb760e01b8152600490fd5b61357e610a189186945061314d565b604051632f0b561760e21b81526001600160a01b039093166004840152602483019390935260448201929092529081906064820190565b9192901561361757508151156135c9575090565b3b156135d25790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b82519091501561362a5750805190602001fd5b60405162461bcd60e51b815260206004820152908190610a18906024830190612467565b93946001600160a01b03808416959194818316949391926000908289880361395a575b50508087156138b4575b847f000000000000000000000000499a9f249ec4c8ea190bebbfd96f9a83bf4f6e52166136a784613a3e565b90803b1561039d57604080516346f9647360e11b81526001600160a01b0390991660048a01526001600160601b039092166024890152909690829082908183816044810103925af180156138aa5761389b575b5090855197838952828a600080516020613b638339815191526020809ca3156137f757508451632d182be560e21b8152600481018a90526001600160a01b0384166024820152306044820152908782606481847f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c68a165af1908115610a4f57509087916137ce575b50505b87156137bd5783518881529586015216927ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db9190a490565b835163f3c41a2b60e01b8152600490fd5b813d83116137f0575b6137e18183612688565b8101031261048c578538613782565b503d6137d7565b8551635d043b2960e11b815260048101919091526001600160a01b0384166024820152306044820152919850908681606481857f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c689165af19182156138905791613863575b5096613785565b90508581813d8311613889575b61387a8183612688565b8101031261048c57513861385c565b503d613870565b8551903d90823e3d90fd5b6138a490612620565b386136fa565b87513d84823e3d90fd5b604051636c82bbbf60e11b81523060048201529091506020816024817f0000000000000000000000007624e0a373b8c77b07e5d5242fd7a194ecc9a4c689165afa801561394f57829061391c575b613916915061390f612f3f565b9084613033565b9061367b565b506020813d8211613947575b8161393560209383612688565b810103126103cf576139169051613902565b3d9150613928565b6040513d84823e3d90fd5b61396491876127cf565b3882613671565b6001600160a01b037f000000000000000000000000499a9f249ec4c8ea190bebbfd96f9a83bf4f6e528116916139a084613a3e565b833b1561048c57604051626c096960e61b81526001600160a01b03831660048201526001600160601b0391909116602482015260009384908290604490829084905af18015613a3357613a0d575b50600080516020613b63833981519152916020916040519586521693a3565b9160209193613a2a600080516020613b6383398151915294612620565b939150916139ee565b6040513d86823e3d90fd5b6001600160601b0390818111613a52571690565b60405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203960448201526536206269747360d01b6064820152608490fd5b916001600160a01b03907f000000000000000000000000499a9f249ec4c8ea190bebbfd96f9a83bf4f6e528216613adc82613a3e565b94813b1561048c5760648491600080946001600160601b03604051988996879563c661667d60e01b8752169a8b6004870152169a8b60248601521660448401525af1908115612edc57600080516020613b6383398151915292602092613b47575b50604051908152a3565b613b5090612620565b38613b3d565b808210156131c157509056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa264697066735822122051df9205aef21eda3cc91d0ccc148b45a8c6f88eaf5720eb4d9e283529a9f7a964736f6c63430008130033
[ 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.