ERC-20
Token Contract
Overview
Max Total Supply
1,266.702220407165545419 fWETH
Holders
810 (0.00%)
Market
Onchain Market Cap
$0.00
Circulating Supply Market Cap
-
Other Info
Token Contract (WITH 18 Decimals)
Balance
0.000097187427186465 fWETHValue
$0.00Loading...
Loading
Loading...
Loading
Loading...
Loading
# | Exchange | Pair | Price | 24H Volume | % Volume |
---|
Contract Name:
fTokenNativeUnderlying
Compiler Version
v0.8.21+commit.d9974bed
Optimization Enabled:
Yes with 10000000 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol"; import { FixedPointMathLib } from "solmate/src/utils/FixedPointMathLib.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { SafeTransfer } from "../../../../libraries/safeTransfer.sol"; import { LiquiditySlotsLink } from "../../../../libraries/liquiditySlotsLink.sol"; import { ErrorTypes } from "../../errorTypes.sol"; import { fTokenCore, fTokenAdmin, fToken } from "../main.sol"; import { IWETH9 } from "../../interfaces/external/iWETH9.sol"; import { IFluidLendingFactory } from "../../interfaces/iLendingFactory.sol"; import { IFTokenAdmin, IFTokenNativeUnderlying, IFToken } from "../../interfaces/iFToken.sol"; import { IFluidLiquidity } from "../../../../liquidity/interfaces/iLiquidity.sol"; /// @dev overrides certain methods from the inherited fToken used as base contract to make them compatible with /// the native token being used as underlying. abstract contract fTokenNativeUnderlyingOverrides is fToken, IFTokenNativeUnderlying { using FixedPointMathLib for uint256; /// @inheritdoc IFTokenNativeUnderlying address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev gets asset address for liquidity slot links, overridden to set native token address function _getLiquiditySlotLinksAsset() internal view virtual override returns (address) { return NATIVE_TOKEN_ADDRESS; } /// @dev Gets current Liquidity underlying token balance function _getLiquidityUnderlyingBalance() internal view virtual override returns (uint256) { return address(LIQUIDITY).balance; } /// @inheritdoc IFTokenAdmin function rescueFunds(address token_) external virtual override(IFTokenAdmin, fTokenAdmin) nonReentrant { _checkIsLendingFactoryAuth(); if (token_ == NATIVE_TOKEN_ADDRESS) { Address.sendValue(payable(address(LIQUIDITY)), address(this).balance); } else { SafeTransfer.safeTransfer(address(token_), address(LIQUIDITY), IERC20(token_).balanceOf(address(this))); } emit LogRescueFunds(token_); } /*////////////////////////////////////////////////////////////// REWARDS //////////////////////////////////////////////////////////////*/ /// @inheritdoc fTokenAdmin function rebalance() external payable virtual override(IFTokenAdmin, fTokenAdmin) nonReentrant returns (uint256 assets_) { if (msg.sender != _rebalancer) { revert FluidLendingError(ErrorTypes.fToken__NotRebalancer); } // calculating difference in assets. if liquidity balance is bigger it'll throw which is an expected behaviour assets_ = totalAssets() - _getLiquidityBalance(); if (msg.value < assets_) { assets_ = msg.value; } else if (msg.value > assets_) { // send back overfunded msg.value amount Address.sendValue(payable(msg.sender), msg.value - assets_); } // send funds to Liquidity protocol to generate yield uint256 liquidityExchangePrice_ = _depositToLiquidity(assets_, new bytes(0)); // update the exchange prices, always updating on storage _updateRates(liquidityExchangePrice_, true); // no shares are minted when funding fToken contract for rewards emit LogRebalance(assets_); } /*////////////////////////////////////////////////////////////// DEPOSIT //////////////////////////////////////////////////////////////*/ /// @inheritdoc fTokenCore function _depositToLiquidity( uint256 assets_, bytes memory liquidityCallbackData_ ) internal virtual override returns (uint256 exchangePrice_) { // send funds to Liquidity protocol to generate yield, send along msg.value (exchangePrice_, ) = LIQUIDITY.operate{ value: assets_ }( NATIVE_TOKEN_ADDRESS, // deposit to Liquidity is always in native, also if user input is wrapped token SafeCast.toInt256(assets_), 0, address(0), address(0), liquidityCallbackData_ // callback data. -> "from" for transferFrom in `liquidityCallback` ); } /// @inheritdoc fTokenCore function _executeDeposit( uint256 assets_, address receiver_, // liquidityCallbackData_ not needed for native transfer, sent along as msg.value. But used to recognize Permit2 transfers. bytes memory liquidityCallbackData_ ) internal virtual override returns (uint256 sharesMinted_) { // transfer wrapped asset from user to this contract if (liquidityCallbackData_.length > 32) { // liquidityCallbackData_ with length > 32 can only be Permit2 as all others maximally encode from address PERMIT2.transferFrom(msg.sender, address(this), uint160(assets_), address(ASSET)); } else { SafeTransfer.safeTransferFrom(address(ASSET), msg.sender, address(this), assets_); } // convert WETH to native underlying token IWETH9(address(ASSET)).withdraw(assets_); // super._executeDeposit includes check for validAddress receiver_ return super._executeDeposit(assets_, receiver_, new bytes(0)); } /// @dev deposits `msg.value` amount of native token into liquidity and mints shares for `receiver_`. /// Returns amount of `sharesMinted_`. function _executeDepositNative(address receiver_) internal virtual returns (uint256 sharesMinted_) { // super._executeDeposit includes check for validAddress receiver_ return super._executeDeposit(msg.value, receiver_, new bytes(0)); } /*////////////////////////////////////////////////////////////// WITHDRAW //////////////////////////////////////////////////////////////*/ /// @inheritdoc fTokenCore function _withdrawFromLiquidity( uint256 assets_, address receiver_ ) internal virtual override returns (uint256 exchangePrice_) { // get funds back from Liquidity protocol to send to the user (exchangePrice_, ) = LIQUIDITY.operate( NATIVE_TOKEN_ADDRESS, // withdraw from Liquidity is always in native, also if user output is wrapped token -SafeCast.toInt256(assets_), 0, receiver_, address(0), new bytes(0) // callback data -> withdraw doesn't trigger a callback ); } /// @inheritdoc fTokenCore function _executeWithdraw( uint256 assets_, address receiver_, address owner_ ) internal virtual override returns (uint256 sharesBurned_) { // super._executeWithdraw includes check for validAddress(receiver_) // withdraw from liquidity to this contract first to convert withdrawn native token to wrapped native for _receiver. sharesBurned_ = super._executeWithdraw(assets_, address(this), owner_); // convert received native underlying token to WETH and transfer to receiver_ IWETH9(address(ASSET)).deposit{ value: assets_ }(); SafeTransfer.safeTransfer(address(ASSET), receiver_, assets_); } /// @dev withdraws `assets_` from liquidity to `receiver_` and burns shares from `owner_`. /// Returns amount of `sharesBurned_`. function _executeWithdrawNative( uint256 assets_, address receiver_, address owner_ ) internal virtual returns (uint256 sharesBurned_) { // super._executeWithdraw includes check for validAddress(receiver_) return super._executeWithdraw(assets_, receiver_, owner_); } } /// @notice implements deposit / mint / withdraw / redeem actions with Native token being used as interaction token. abstract contract fTokenNativeUnderlyingActions is fTokenNativeUnderlyingOverrides { /*////////////////////////////////////////////////////////////// DEPOSIT //////////////////////////////////////////////////////////////*/ /// @inheritdoc IFTokenNativeUnderlying function depositNative(address receiver_) public payable nonReentrant returns (uint256 shares_) { shares_ = _executeDepositNative(receiver_); } /// @inheritdoc IFTokenNativeUnderlying function depositNative(address receiver_, uint256 minAmountOut_) external payable returns (uint256 shares_) { shares_ = depositNative(receiver_); _revertIfBelowMinAmountOut(shares_, minAmountOut_); } /*////////////////////////////////////////////////////////////// MINT //////////////////////////////////////////////////////////////*/ /// @inheritdoc IFTokenNativeUnderlying function mintNative(uint256 shares_, address receiver_) public payable nonReentrant returns (uint256 assets_) { // No need to check for rounding error, previewMint rounds up. assets_ = previewMint(shares_); if (msg.value < assets_) { // not enough msg.value sent along to cover mint shares amount revert FluidLendingError(ErrorTypes.fTokenNativeUnderlying__TransferInsufficient); } _executeDepositNative(receiver_); } /// @inheritdoc IFTokenNativeUnderlying function mintNative( uint256 shares_, address receiver_, uint256 maxAssets_ ) external payable returns (uint256 assets_) { assets_ = mintNative(shares_, receiver_); _revertIfAboveMaxAmount(assets_, maxAssets_); } /*////////////////////////////////////////////////////////////// WITHDRAW //////////////////////////////////////////////////////////////*/ /// @inheritdoc IFTokenNativeUnderlying function withdrawNative( uint256 assets_, address receiver_, address owner_ ) public nonReentrant returns (uint256 shares_) { if (assets_ == type(uint256).max) { assets_ = previewRedeem(balanceOf(msg.sender)); } shares_ = _executeWithdrawNative(assets_, receiver_, owner_); if (msg.sender != owner_) { _spendAllowance(owner_, msg.sender, shares_); } } /// @inheritdoc IFTokenNativeUnderlying function withdrawNative( uint256 assets_, address receiver_, address owner_, uint256 maxSharesBurn_ ) external returns (uint256 shares_) { shares_ = withdrawNative(assets_, receiver_, owner_); _revertIfAboveMaxAmount(shares_, maxSharesBurn_); } /*////////////////////////////////////////////////////////////// REDEEM //////////////////////////////////////////////////////////////*/ /// @inheritdoc IFTokenNativeUnderlying function redeemNative( uint256 shares_, address receiver_, address owner_ ) public nonReentrant returns (uint256 assets_) { if (shares_ == type(uint256).max) { shares_ = balanceOf(msg.sender); } assets_ = previewRedeem(shares_); uint256 burnedShares_ = _executeWithdrawNative(assets_, receiver_, owner_); if (msg.sender != owner_) { _spendAllowance(owner_, msg.sender, burnedShares_); } } /// @inheritdoc IFTokenNativeUnderlying function redeemNative( uint256 shares_, address receiver_, address owner_, uint256 minAmountOut_ ) external returns (uint256 assets_) { assets_ = redeemNative(shares_, receiver_, owner_); _revertIfBelowMinAmountOut(assets_, minAmountOut_); } } /// @notice fTokens support EIP-2612 permit approvals via signature so withdrawals are possible with signature. /// This contract implements those withdrawals for a native underlying asset. abstract contract fTokenNativeUnderlyingEIP2612Withdrawals is fTokenNativeUnderlyingActions { /// @inheritdoc IFTokenNativeUnderlying function withdrawWithSignatureNative( uint256 sharesToPermit_, uint256 assets_, address receiver_, address owner_, uint256 maxSharesBurn_, uint256 deadline_, bytes calldata signature_ ) external nonReentrant returns (uint256 shares_) { // @dev logic below is exactly the same as in {fTokenEIP2612Withdrawals-withdrawWithSignature}, just using // _executeWithdrawNative instead of _executeWithdraw if (msg.sender == owner_) { // no sense in operating with permit if msg.sender is owner. should call normal `withdraw()` instead. revert FluidLendingError(ErrorTypes.fToken__PermitFromOwnerCall); } // create allowance through signature_ _allowViaPermitEIP2612(owner_, sharesToPermit_, deadline_, signature_); // execute withdraw to get shares_ to spend amount shares_ = _executeWithdrawNative(assets_, receiver_, owner_); _revertIfAboveMaxAmount(shares_, maxSharesBurn_); _spendAllowance(owner_, msg.sender, shares_); } /// @inheritdoc IFTokenNativeUnderlying function redeemWithSignatureNative( uint256 shares_, address receiver_, address owner_, uint256 minAmountOut_, uint256 deadline_, bytes calldata signature_ ) external nonReentrant returns (uint256 assets_) { // @dev logic below is exactly the same as in {fTokenEIP2612Withdrawals-redeemWithSignature}, just using // _executeWithdrawNative instead of _executeWithdraw if (msg.sender == owner_) { // no sense in operating with permit if msg.sender is owner. should call normal `redeem()` instead. revert FluidLendingError(ErrorTypes.fToken__PermitFromOwnerCall); } assets_ = previewRedeem(shares_); _revertIfBelowMinAmountOut(assets_, minAmountOut_); // create allowance through signature_ _allowViaPermitEIP2612(owner_, shares_, deadline_, signature_); // execute withdraw to get actual shares to spend amount uint256 sharesToSpend_ = _executeWithdrawNative(assets_, receiver_, owner_); _spendAllowance(owner_, msg.sender, sharesToSpend_); } } /// @notice Same as the {fToken} contract but with support for native token as underlying asset. /// Actual underlying asset is the wrapped native ERC20 version (e.g. WETH), which acts like any other fToken. /// But in addition the fTokenNativeUnderlying also has methods for doing all the same actions via the native token. contract fTokenNativeUnderlying is fTokenNativeUnderlyingEIP2612Withdrawals { /// @param liquidity_ liquidity contract address /// @param lendingFactory_ lending factory contract address /// @param weth_ address of wrapped native token (e.g. WETH) constructor( IFluidLiquidity liquidity_, IFluidLendingFactory lendingFactory_, IWETH9 weth_ ) fToken(liquidity_, lendingFactory_, IERC20(address(weth_))) {} /// @inheritdoc fToken function liquidityCallback( address /** token_ */, uint256 /** amount_ */, bytes calldata /** data_ */ ) external virtual override(IFToken, fToken) { // not needed because msg.value is used directly revert FluidLendingError(ErrorTypes.fTokenNativeUnderlying__UnexpectedLiquidityCallback); } receive() external payable {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.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.8.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]. * * 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}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * 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 value {ERC20} uses, unless this function is * 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.8.0) (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/cryptography/EIP712.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`. * However, to ensure consistency with the upgradeable transpiler, we will continue * to reserve a slot. * @custom:oz-renamed-from _PERMIT_TYPEHASH */ // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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.6.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 (last updated v4.8.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 * ==== * * [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://diligence.consensys.net/posts/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.5.11/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 v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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.8.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) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @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) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.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]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // 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 _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @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) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, 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); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.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) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 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 10, 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 * 8) < value ? 1 : 0); } } }
// 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.8.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/Math.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 `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); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.21; interface IProxy { function setAdmin(address newAdmin_) external; function setDummyImplementation(address newDummyImplementation_) external; function addImplementation(address implementation_, bytes4[] calldata sigs_) external; function removeImplementation(address implementation_) external; function getAdmin() external view returns (address); function getDummyImplementation() external view returns (address); function getImplementationSigs(address impl_) external view returns (bytes4[] memory); function getSigsImplementation(bytes4 sig_) external view returns (address); function readFromStorage(bytes32 slot_) external view returns (uint256 result_); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; /// @title library that represents a number in BigNumber(coefficient and exponent) format to store in smaller bits. /// @notice the number is divided into two parts: a coefficient and an exponent. This comes at a cost of losing some precision /// at the end of the number because the exponent simply fills it with zeroes. This precision is oftentimes negligible and can /// result in significant gas cost reduction due to storage space reduction. /// Also note, a valid big number is as follows: if the exponent is > 0, then coefficient last bits should be occupied to have max precision. /// @dev roundUp is more like a increase 1, which happens everytime for the same number. /// roundDown simply sets trailing digits after coefficientSize to zero (floor), only once for the same number. library BigMathMinified { /// @dev constants to use for `roundUp` input param to increase readability bool internal constant ROUND_DOWN = false; bool internal constant ROUND_UP = true; /// @dev converts `normal` number to BigNumber with `exponent` and `coefficient` (or precision). /// e.g.: /// 5035703444687813576399599 (normal) = (coefficient[32bits], exponent[8bits])[40bits] /// 5035703444687813576399599 (decimal) => 10000101010010110100000011111011110010100110100000000011100101001101001101011101111 (binary) /// => 10000101010010110100000011111011000000000000000000000000000000000000000000000000000 /// ^-------------------- 51(exponent) -------------- ^ /// coefficient = 1000,0101,0100,1011,0100,0000,1111,1011 (2236301563) /// exponent = 0011,0011 (51) /// bigNumber = 1000,0101,0100,1011,0100,0000,1111,1011,0011,0011 (572493200179) /// /// @param normal number which needs to be converted into Big Number /// @param coefficientSize at max how many bits of precision there should be (64 = uint64 (64 bits precision)) /// @param exponentSize at max how many bits of exponent there should be (8 = uint8 (8 bits exponent)) /// @param roundUp signals if result should be rounded down or up /// @return bigNumber converted bigNumber (coefficient << exponent) function toBigNumber( uint256 normal, uint256 coefficientSize, uint256 exponentSize, bool roundUp ) internal pure returns (uint256 bigNumber) { assembly { let lastBit_ let number_ := normal if gt(number_, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { number_ := shr(0x80, number_) lastBit_ := 0x80 } if gt(number_, 0xFFFFFFFFFFFFFFFF) { number_ := shr(0x40, number_) lastBit_ := add(lastBit_, 0x40) } if gt(number_, 0xFFFFFFFF) { number_ := shr(0x20, number_) lastBit_ := add(lastBit_, 0x20) } if gt(number_, 0xFFFF) { number_ := shr(0x10, number_) lastBit_ := add(lastBit_, 0x10) } if gt(number_, 0xFF) { number_ := shr(0x8, number_) lastBit_ := add(lastBit_, 0x8) } if gt(number_, 0xF) { number_ := shr(0x4, number_) lastBit_ := add(lastBit_, 0x4) } if gt(number_, 0x3) { number_ := shr(0x2, number_) lastBit_ := add(lastBit_, 0x2) } if gt(number_, 0x1) { lastBit_ := add(lastBit_, 1) } if gt(number_, 0) { lastBit_ := add(lastBit_, 1) } if lt(lastBit_, coefficientSize) { // for throw exception lastBit_ := coefficientSize } let exponent := sub(lastBit_, coefficientSize) let coefficient := shr(exponent, normal) if and(roundUp, gt(exponent, 0)) { // rounding up is only needed if exponent is > 0, as otherwise the coefficient fully holds the original number coefficient := add(coefficient, 1) if eq(shl(coefficientSize, 1), coefficient) { // case were coefficient was e.g. 111, with adding 1 it became 1000 (in binary) and coefficientSize 3 bits // final coefficient would exceed it's size. -> reduce coefficent to 100 and increase exponent by 1. coefficient := shl(sub(coefficientSize, 1), 1) exponent := add(exponent, 1) } } if iszero(lt(exponent, shl(exponentSize, 1))) { // if exponent is >= exponentSize, the normal number is too big to fit within // BigNumber with too small sizes for coefficient and exponent revert(0, 0) } bigNumber := shl(exponentSize, coefficient) bigNumber := add(bigNumber, exponent) } } /// @dev get `normal` number from `bigNumber`, `exponentSize` and `exponentMask` function fromBigNumber( uint256 bigNumber, uint256 exponentSize, uint256 exponentMask ) internal pure returns (uint256 normal) { assembly { let coefficient := shr(exponentSize, bigNumber) let exponent := and(bigNumber, exponentMask) normal := shl(exponent, coefficient) } } /// @dev gets the most significant bit `lastBit` of a `normal` number (length of given number of binary format). /// e.g. /// 5035703444687813576399599 = 10000101010010110100000011111011110010100110100000000011100101001101001101011101111 /// lastBit = ^--------------------------------- 83 ----------------------------------------^ function mostSignificantBit(uint256 normal) internal pure returns (uint lastBit) { assembly { let number_ := normal if gt(normal, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { number_ := shr(0x80, number_) lastBit := 0x80 } if gt(number_, 0xFFFFFFFFFFFFFFFF) { number_ := shr(0x40, number_) lastBit := add(lastBit, 0x40) } if gt(number_, 0xFFFFFFFF) { number_ := shr(0x20, number_) lastBit := add(lastBit, 0x20) } if gt(number_, 0xFFFF) { number_ := shr(0x10, number_) lastBit := add(lastBit, 0x10) } if gt(number_, 0xFF) { number_ := shr(0x8, number_) lastBit := add(lastBit, 0x8) } if gt(number_, 0xF) { number_ := shr(0x4, number_) lastBit := add(lastBit, 0x4) } if gt(number_, 0x3) { number_ := shr(0x2, number_) lastBit := add(lastBit, 0x2) } if gt(number_, 0x1) { lastBit := add(lastBit, 1) } if gt(number_, 0) { lastBit := add(lastBit, 1) } } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; library LibsErrorTypes { /***********************************| | LiquidityCalcs | |__________________________________*/ /// @notice thrown when supply or borrow exchange price is zero at calc token data (token not configured yet) uint256 internal constant LiquidityCalcs__ExchangePriceZero = 70001; /// @notice thrown when rate data is set to a version that is not implemented uint256 internal constant LiquidityCalcs__UnsupportedRateVersion = 70002; /***********************************| | SafeTransfer | |__________________________________*/ /// @notice thrown when safe transfer from for an ERC20 fails uint256 internal constant SafeTransfer__TransferFromFailed = 71001; /// @notice thrown when safe transfer for an ERC20 fails uint256 internal constant SafeTransfer__TransferFailed = 71002; }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; import { LibsErrorTypes as ErrorTypes } from "./errorTypes.sol"; import { LiquiditySlotsLink } from "./liquiditySlotsLink.sol"; import { BigMathMinified } from "./bigMathMinified.sol"; /// @notice implements calculation methods used for Fluid liquidity such as updated exchange prices, /// borrow rate, withdrawal / borrow limits, revenue amount. library LiquidityCalcs { error FluidLiquidityCalcsError(uint256 errorId_); /// @notice emitted if the calculated borrow rate surpassed max borrow rate (16 bits) and was capped at maximum value 65535 event BorrowRateMaxCap(); /// @dev constants as from Liquidity variables.sol uint256 internal constant EXCHANGE_PRICES_PRECISION = 1e12; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; // constants used for BigMath conversion from and to storage uint256 internal constant DEFAULT_EXPONENT_SIZE = 8; uint256 internal constant DEFAULT_EXPONENT_MASK = 0xFF; uint256 internal constant FOUR_DECIMALS = 1e4; uint256 internal constant TWELVE_DECIMALS = 1e12; uint256 internal constant X14 = 0x3fff; uint256 internal constant X15 = 0x7fff; uint256 internal constant X16 = 0xffff; uint256 internal constant X18 = 0x3ffff; uint256 internal constant X24 = 0xffffff; uint256 internal constant X33 = 0x1ffffffff; uint256 internal constant X64 = 0xffffffffffffffff; /////////////////////////////////////////////////////////////////////////// ////////// CALC EXCHANGE PRICES ///////// /////////////////////////////////////////////////////////////////////////// /// @dev calculates interest (exchange prices) for a token given its' exchangePricesAndConfig from storage. /// @param exchangePricesAndConfig_ exchange prices and config packed uint256 read from storage /// @return supplyExchangePrice_ updated supplyExchangePrice /// @return borrowExchangePrice_ updated borrowExchangePrice function calcExchangePrices( uint256 exchangePricesAndConfig_ ) internal view returns (uint256 supplyExchangePrice_, uint256 borrowExchangePrice_) { // Extracting exchange prices supplyExchangePrice_ = (exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_SUPPLY_EXCHANGE_PRICE) & X64; borrowExchangePrice_ = (exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_BORROW_EXCHANGE_PRICE) & X64; if (supplyExchangePrice_ == 0 || borrowExchangePrice_ == 0) { revert FluidLiquidityCalcsError(ErrorTypes.LiquidityCalcs__ExchangePriceZero); } uint256 temp_ = exchangePricesAndConfig_ & X16; // temp_ = borrowRate unchecked { // last timestamp can not be > current timestamp uint256 secondsSinceLastUpdate_ = block.timestamp - ((exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_LAST_TIMESTAMP) & X33); uint256 borrowRatio_ = (exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_BORROW_RATIO) & X15; if (secondsSinceLastUpdate_ == 0 || temp_ == 0 || borrowRatio_ == 1) { // if no time passed, borrow rate is 0, or no raw borrowings: no exchange price update needed // (if borrowRatio_ == 1 means there is only borrowInterestFree, as first bit is 1 and rest is 0) return (supplyExchangePrice_, borrowExchangePrice_); } // calculate new borrow exchange price. // formula borrowExchangePriceIncrease: previous price * borrow rate * secondsSinceLastUpdate_. // nominator is max uint112 (uint64 * uint16 * uint32). Divisor can not be 0. borrowExchangePrice_ += (borrowExchangePrice_ * temp_ * secondsSinceLastUpdate_) / (SECONDS_PER_YEAR * FOUR_DECIMALS); // FOR SUPPLY EXCHANGE PRICE: // all yield paid by borrowers (in mode with interest) goes to suppliers in mode with interest. // formula: previous price * supply rate * secondsSinceLastUpdate_. // where supply rate = (borrow rate - revenueFee%) * ratioSupplyYield. And // ratioSupplyYield = utilization * supplyRatio * borrowRatio // // Example: // supplyRawInterest is 80, supplyInterestFree is 20. totalSupply is 100. BorrowedRawInterest is 50. // BorrowInterestFree is 10. TotalBorrow is 60. borrow rate 40%, revenueFee 10%. // yield is 10 (so half a year must have passed). // supplyRawInterest must become worth 89. totalSupply must become 109. BorrowedRawInterest must become 60. // borrowInterestFree must still be 10. supplyInterestFree still 20. totalBorrow 70. // supplyExchangePrice would have to go from 1 to 1,125 (+ 0.125). borrowExchangePrice from 1 to 1,2 (+0.2). // utilization is 60%. supplyRatio = 20 / 80 = 25% (only 80% of lenders receiving yield). // borrowRatio = 10 / 50 = 20% (only 83,333% of borrowers paying yield): // x of borrowers paying yield = 100% - (20 / (100 + 20)) = 100% - 16.6666666% = 83,333%. // ratioSupplyYield = 60% * 83,33333% * (100% + 20%) = 62,5% // supplyRate = (40% * (100% - 10%)) * = 36% * 62,5% = 22.5% // increase in supplyExchangePrice, assuming 100 as previous price. // 100 * 22,5% * 1/2 (half a year) = 0,1125. // cross-check supplyRawInterest worth = 80 * 1.1125 = 89. totalSupply worth = 89 + 20. // -------------- 1. calculate ratioSupplyYield -------------------------------- // step1: utilization * supplyRatio (or actually part of lenders receiving yield) // temp_ => supplyRatio (in 1e2: 100% = 10_000; 1% = 100 -> max value 16_383) // if first bit 0 then ratio is supplyInterestFree / supplyWithInterest (supplyWithInterest is bigger) // else ratio is supplyWithInterest / supplyInterestFree (supplyInterestFree is bigger) temp_ = (exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_SUPPLY_RATIO) & X15; if (temp_ == 1) { // if no raw supply: no exchange price update needed // (if supplyRatio_ == 1 means there is only supplyInterestFree, as first bit is 1 and rest is 0) return (supplyExchangePrice_, borrowExchangePrice_); } // ratioSupplyYield precision is 1e27 as 100% for increased precision when supplyInterestFree > supplyWithInterest if (temp_ & 1 == 1) { // ratio is supplyWithInterest / supplyInterestFree (supplyInterestFree is bigger) temp_ = temp_ >> 1; // Note: case where temp_ == 0 (only supplyInterestFree, no yield) already covered by early return // in the if statement a little above. // based on above example but supplyRawInterest is 20, supplyInterestFree is 80. no fee. // supplyRawInterest must become worth 30. totalSupply must become 110. // supplyExchangePrice would have to go from 1 to 1,5. borrowExchangePrice from 1 to 1,2. // so ratioSupplyYield must come out as 2.5 (250%). // supplyRatio would be (20 * 10_000 / 80) = 2500. but must be inverted. temp_ = (1e27 * FOUR_DECIMALS) / temp_; // e.g. 1e31 / 2500 = 4e27. (* 1e27 for precision) // e.g. 5_000 * (1e27 + 4e27) / 1e27 = 25_000 (=250%). temp_ = // utilization * (100% + 100% / supplyRatio) (((exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_UTILIZATION) & X14) * (1e27 + temp_)) / // extract utilization (max 16_383 so there is no way this can overflow). (FOUR_DECIMALS); // max possible value of temp_ here is 16383 * (1e27 + 1e31) / 1e4 = ~1.64e31 } else { // ratio is supplyInterestFree / supplyWithInterest (supplyWithInterest is bigger) temp_ = temp_ >> 1; // if temp_ == 0 then only supplyWithInterest => full yield. temp_ is already 0 // e.g. 5_000 * 10_000 + (20 * 10_000 / 80) / 10_000 = 5000 * 12500 / 10000 = 6250 (=62.5%). temp_ = // 1e27 * utilization * (100% + supplyRatio) / 100% (1e27 * ((exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_UTILIZATION) & X14) * // extract utilization (max 16_383 so there is no way this can overflow). (FOUR_DECIMALS + temp_)) / (FOUR_DECIMALS * FOUR_DECIMALS); // max possible temp_ value: 1e27 * 16383 * 2e4 / 1e8 = 3.2766e27 } // from here temp_ => ratioSupplyYield (utilization * supplyRatio part) scaled by 1e27. max possible value ~1.64e31 // step2 of ratioSupplyYield: add borrowRatio (only x% of borrowers paying yield) if (borrowRatio_ & 1 == 1) { // ratio is borrowWithInterest / borrowInterestFree (borrowInterestFree is bigger) borrowRatio_ = borrowRatio_ >> 1; // borrowRatio_ => x of total bororwers paying yield. scale to 1e27. // Note: case where borrowRatio_ == 0 (only borrowInterestFree, no yield) already covered // at the beginning of the method by early return if `borrowRatio_ == 1`. // based on above example but borrowRawInterest is 10, borrowInterestFree is 50. no fee. borrowRatio = 20%. // so only 16.66% of borrowers are paying yield. so the 100% - part of the formula is not needed. // x of borrowers paying yield = (borrowRatio / (100 + borrowRatio)) = 16.6666666% // borrowRatio_ => x of total bororwers paying yield. scale to 1e27. borrowRatio_ = (borrowRatio_ * 1e27) / (FOUR_DECIMALS + borrowRatio_); // max value here for borrowRatio_ is (1e31 / (1e4 + 1e4))= 5e26 (= 50% of borrowers paying yield). } else { // ratio is borrowInterestFree / borrowWithInterest (borrowWithInterest is bigger) borrowRatio_ = borrowRatio_ >> 1; // borrowRatio_ => x of total bororwers paying yield. scale to 1e27. // x of borrowers paying yield = 100% - (borrowRatio / (100 + borrowRatio)) = 100% - 16.6666666% = 83,333%. borrowRatio_ = (1e27 - ((borrowRatio_ * 1e27) / (FOUR_DECIMALS + borrowRatio_))); // borrowRatio can never be > 100%. so max subtraction can be 100% - 100% / 200%. // or if borrowRatio_ is 0 -> 100% - 0. or if borrowRatio_ is 1 -> 100% - 1 / 101. // max value here for borrowRatio_ is 1e27 - 0 = 1e27 (= 100% of borrowers paying yield). } // temp_ => ratioSupplyYield. scaled down from 1e25 = 1% each to normal percent precision 1e2 = 1%. // max nominator value is ~1.64e31 * 1e27 = 1.64e58. max result = 1.64e8 temp_ = (FOUR_DECIMALS * temp_ * borrowRatio_) / 1e54; // 2. calculate supply rate // temp_ => supply rate (borrow rate - revenueFee%) * ratioSupplyYield. // division part is done in next step to increase precision. (divided by 2x FOUR_DECIMALS, fee + borrowRate) // Note that all calculation divisions for supplyExchangePrice are rounded down. // Note supply rate can be bigger than the borrowRate, e.g. if there are only few lenders with interest // but more suppliers not earning interest. temp_ = ((exchangePricesAndConfig_ & X16) * // borrow rate temp_ * // ratioSupplyYield (FOUR_DECIMALS - ((exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_FEE) & X14))); // revenueFee // fee can not be > 100%. max possible = 65535 * ~1.64e8 * 1e4 =~1.074774e17. // 3. calculate increase in supply exchange price supplyExchangePrice_ += ((supplyExchangePrice_ * temp_ * secondsSinceLastUpdate_) / (SECONDS_PER_YEAR * FOUR_DECIMALS * FOUR_DECIMALS * FOUR_DECIMALS)); // max possible nominator = max uint 64 * 1.074774e17 * max uint32 = ~8.52e45. Denominator can not be 0. } } /////////////////////////////////////////////////////////////////////////// ////////// CALC REVENUE ///////// /////////////////////////////////////////////////////////////////////////// /// @dev gets the `revenueAmount_` for a token given its' totalAmounts and exchangePricesAndConfig from storage /// and the current balance of the Fluid liquidity contract for the token. /// @param totalAmounts_ total amounts packed uint256 read from storage /// @param exchangePricesAndConfig_ exchange prices and config packed uint256 read from storage /// @param liquidityTokenBalance_ current balance of Liquidity contract (IERC20(token_).balanceOf(address(this))) /// @return revenueAmount_ collectable revenue amount function calcRevenue( uint256 totalAmounts_, uint256 exchangePricesAndConfig_, uint256 liquidityTokenBalance_ ) internal view returns (uint256 revenueAmount_) { // @dev no need to super-optimize this method as it is only used by admin // calculate the new exchange prices based on earned interest (uint256 supplyExchangePrice_, uint256 borrowExchangePrice_) = calcExchangePrices(exchangePricesAndConfig_); // total supply = interest free + with interest converted from raw uint256 totalSupply_ = getTotalSupply(totalAmounts_, supplyExchangePrice_); if (totalSupply_ > 0) { // available revenue: balanceOf(token) + totalBorrowings - totalLendings. revenueAmount_ = liquidityTokenBalance_ + getTotalBorrow(totalAmounts_, borrowExchangePrice_); // ensure there is no possible case because of rounding etc. where this would revert, // explicitly check if > revenueAmount_ = revenueAmount_ > totalSupply_ ? revenueAmount_ - totalSupply_ : 0; // Note: if utilization > 100% (totalSupply < totalBorrow), then all the amount above 100% utilization // can only be revenue. } else { // if supply is 0, then rest of balance can be withdrawn as revenue so that no amounts get stuck revenueAmount_ = liquidityTokenBalance_; } } /////////////////////////////////////////////////////////////////////////// ////////// CALC LIMITS ///////// /////////////////////////////////////////////////////////////////////////// /// @dev calculates withdrawal limit before an operate execution: /// amount of user supply that must stay supplied (not amount that can be withdrawn). /// i.e. if user has supplied 100m and can withdraw 5M, this method returns the 95M, not the withdrawable amount 5M /// @param userSupplyData_ user supply data packed uint256 from storage /// @param userSupply_ current user supply amount already extracted from `userSupplyData_` and converted from BigMath /// @return currentWithdrawalLimit_ current withdrawal limit updated for expansion since last interaction. /// returned value is in raw for with interest mode, normal amount for interest free mode! function calcWithdrawalLimitBeforeOperate( uint256 userSupplyData_, uint256 userSupply_ ) internal view returns (uint256 currentWithdrawalLimit_) { // @dev must support handling the case where timestamp is 0 (config is set but no interactions yet). // first tx where timestamp is 0 will enter `if (lastWithdrawalLimit_ == 0)` because lastWithdrawalLimit_ is not set yet. // returning max withdrawal allowed, which is not exactly right but doesn't matter because the first interaction must be // a deposit anyway. Important is that it would not revert. // Note the first time a deposit brings the user supply amount to above the base withdrawal limit, the active limit // is the fully expanded limit immediately. // extract last set withdrawal limit uint256 lastWithdrawalLimit_ = (userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT) & X64; lastWithdrawalLimit_ = (lastWithdrawalLimit_ >> DEFAULT_EXPONENT_SIZE) << (lastWithdrawalLimit_ & DEFAULT_EXPONENT_MASK); if (lastWithdrawalLimit_ == 0) { // withdrawal limit is not activated. Max withdrawal allowed return 0; } uint256 maxWithdrawableLimit_; uint256 temp_; unchecked { // extract max withdrawable percent of user supply and // calculate maximum withdrawable amount expandPercentage of user supply at full expansion duration elapsed // e.g.: if 10% expandPercentage, meaning 10% is withdrawable after full expandDuration has elapsed. // userSupply_ needs to be atleast 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible). maxWithdrawableLimit_ = (((userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14) * userSupply_) / FOUR_DECIMALS; // time elapsed since last withdrawal limit was set (in seconds) // @dev last process timestamp is guaranteed to exist for withdrawal, as a supply must have happened before. // last timestamp can not be > current timestamp temp_ = block.timestamp - ((userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP) & X33); } // calculate withdrawable amount of expandPercent that is elapsed of expandDuration. // e.g. if 60% of expandDuration has elapsed, then user should be able to withdraw 6% of user supply, down to 94%. // Note: no explicit check for this needed, it is covered by setting minWithdrawalLimit_ if needed. temp_ = (maxWithdrawableLimit_ * temp_) / // extract expand duration: After this, decrement won't happen (user can withdraw 100% of withdraw limit) ((userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_EXPAND_DURATION) & X24); // expand duration can never be 0 // calculate expanded withdrawal limit: last withdrawal limit - withdrawable amount. // Note: withdrawable amount here can grow bigger than userSupply if timeElapsed is a lot bigger than expandDuration, // which would cause the subtraction `lastWithdrawalLimit_ - withdrawableAmount_` to revert. In that case, set 0 // which will cause minimum (fully expanded) withdrawal limit to be set in lines below. unchecked { // underflow explicitly checked & handled currentWithdrawalLimit_ = lastWithdrawalLimit_ > temp_ ? lastWithdrawalLimit_ - temp_ : 0; // calculate minimum withdrawal limit: minimum amount of user supply that must stay supplied at full expansion. // subtraction can not underflow as maxWithdrawableLimit_ is a percentage amount (<=100%) of userSupply_ temp_ = userSupply_ - maxWithdrawableLimit_; } // if withdrawal limit is decreased below minimum then set minimum // (e.g. when more than expandDuration time has elapsed) if (temp_ > currentWithdrawalLimit_) { currentWithdrawalLimit_ = temp_; } } /// @dev calculates withdrawal limit after an operate execution: /// amount of user supply that must stay supplied (not amount that can be withdrawn). /// i.e. if user has supplied 100m and can withdraw 5M, this method returns the 95M, not the withdrawable amount 5M /// @param userSupplyData_ user supply data packed uint256 from storage /// @param userSupply_ current user supply amount already extracted from `userSupplyData_` and added / subtracted with the executed operate amount /// @param newWithdrawalLimit_ current withdrawal limit updated for expansion since last interaction, result from `calcWithdrawalLimitBeforeOperate` /// @return withdrawalLimit_ updated withdrawal limit that should be written to storage. returned value is in /// raw for with interest mode, normal amount for interest free mode! function calcWithdrawalLimitAfterOperate( uint256 userSupplyData_, uint256 userSupply_, uint256 newWithdrawalLimit_ ) internal pure returns (uint256) { // temp_ => base withdrawal limit. below this, maximum withdrawals are allowed uint256 temp_ = (userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT) & X18; temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK); // if user supply is below base limit then max withdrawals are allowed if (userSupply_ < temp_) { return 0; } // temp_ => withdrawal limit expandPercent (is in 1e2 decimals) temp_ = (userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14; unchecked { // temp_ => minimum withdrawal limit: userSupply - max withdrawable limit (userSupply * expandPercent)) // userSupply_ needs to be atleast 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible). // subtraction can not underflow as maxWithdrawableLimit_ is a percentage amount (<=100%) of userSupply_ temp_ = userSupply_ - ((userSupply_ * temp_) / FOUR_DECIMALS); } // if new (before operation) withdrawal limit is less than minimum limit then set minimum limit. // e.g. can happen on new deposits. withdrawal limit is instantly fully expanded in a scenario where // increased deposit amount outpaces withrawals. if (temp_ > newWithdrawalLimit_) { return temp_; } return newWithdrawalLimit_; } /// @dev calculates borrow limit before an operate execution: /// total amount user borrow can reach (not borrowable amount in current operation). /// i.e. if user has borrowed 50M and can still borrow 5M, this method returns the total 55M, not the borrowable amount 5M /// @param userBorrowData_ user borrow data packed uint256 from storage /// @param userBorrow_ current user borrow amount already extracted from `userBorrowData_` /// @return currentBorrowLimit_ current borrow limit updated for expansion since last interaction. returned value is in /// raw for with interest mode, normal amount for interest free mode! function calcBorrowLimitBeforeOperate( uint256 userBorrowData_, uint256 userBorrow_ ) internal view returns (uint256 currentBorrowLimit_) { // @dev must support handling the case where timestamp is 0 (config is set but no interactions yet) -> base limit. // first tx where timestamp is 0 will enter `if (maxExpandedBorrowLimit_ < baseBorrowLimit_)` because `userBorrow_` and thus // `maxExpansionLimit_` and thus `maxExpandedBorrowLimit_` is 0 and `baseBorrowLimit_` can not be 0. // temp_ = extract borrow expand percent (is in 1e2 decimals) uint256 temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14; uint256 maxExpansionLimit_; uint256 maxExpandedBorrowLimit_; unchecked { // calculate max expansion limit: Max amount limit can expand to since last interaction // userBorrow_ needs to be atleast 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible). maxExpansionLimit_ = ((userBorrow_ * temp_) / FOUR_DECIMALS); // calculate max borrow limit: Max point limit can increase to since last interaction maxExpandedBorrowLimit_ = userBorrow_ + maxExpansionLimit_; } // currentBorrowLimit_ = extract base borrow limit currentBorrowLimit_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18; currentBorrowLimit_ = (currentBorrowLimit_ >> DEFAULT_EXPONENT_SIZE) << (currentBorrowLimit_ & DEFAULT_EXPONENT_MASK); if (maxExpandedBorrowLimit_ < currentBorrowLimit_) { return currentBorrowLimit_; } // time elapsed since last borrow limit was set (in seconds) unchecked { // temp_ = timeElapsed_ (last timestamp can not be > current timestamp) temp_ = block.timestamp - ((userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP) & X33); // extract last udpate timestamp } // currentBorrowLimit_ = expandedBorrowableAmount + extract last set borrow limit currentBorrowLimit_ = // calculate borrow limit expansion since last interaction for `expandPercent` that is elapsed of `expandDuration`. // divisor is extract expand duration (after this, full expansion to expandPercentage happened). ((maxExpansionLimit_ * temp_) / ((userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_EXPAND_DURATION) & X24)) + // expand duration can never be 0 // extract last set borrow limit BigMathMinified.fromBigNumber( (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT) & X64, DEFAULT_EXPONENT_SIZE, DEFAULT_EXPONENT_MASK ); // if timeElapsed is bigger than expandDuration, new borrow limit would be > max expansion, // so set to `maxExpandedBorrowLimit_` in that case. // also covers the case where last process timestamp = 0 (timeElapsed would simply be very big) if (currentBorrowLimit_ > maxExpandedBorrowLimit_) { currentBorrowLimit_ = maxExpandedBorrowLimit_; } // temp_ = extract hard max borrow limit. Above this user can never borrow (not expandable above) temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18; temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK); if (currentBorrowLimit_ > temp_) { currentBorrowLimit_ = temp_; } } /// @dev calculates borrow limit after an operate execution: /// total amount user borrow can reach (not borrowable amount in current operation). /// i.e. if user has borrowed 50M and can still borrow 5M, this method returns the total 55M, not the borrowable amount 5M /// @param userBorrowData_ user borrow data packed uint256 from storage /// @param userBorrow_ current user borrow amount already extracted from `userBorrowData_` and added / subtracted with the executed operate amount /// @param newBorrowLimit_ current borrow limit updated for expansion since last interaction, result from `calcBorrowLimitBeforeOperate` /// @return borrowLimit_ updated borrow limit that should be written to storage. /// returned value is in raw for with interest mode, normal amount for interest free mode! function calcBorrowLimitAfterOperate( uint256 userBorrowData_, uint256 userBorrow_, uint256 newBorrowLimit_ ) internal pure returns (uint256 borrowLimit_) { // temp_ = extract borrow expand percent uint256 temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14; // (is in 1e2 decimals) unchecked { // borrowLimit_ = calculate maximum borrow limit at full expansion. // userBorrow_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible). borrowLimit_ = userBorrow_ + ((userBorrow_ * temp_) / FOUR_DECIMALS); } // temp_ = extract base borrow limit temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18; temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK); if (borrowLimit_ < temp_) { // below base limit, borrow limit is always base limit return temp_; } // temp_ = extract hard max borrow limit. Above this user can never borrow (not expandable above) temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18; temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK); // make sure fully expanded borrow limit is not above hard max borrow limit if (borrowLimit_ > temp_) { borrowLimit_ = temp_; } // if new borrow limit (from before operate) is > max borrow limit, set max borrow limit. // (e.g. on a repay shrinking instantly to fully expanded borrow limit from new borrow amount. shrinking is instant) if (newBorrowLimit_ > borrowLimit_) { return borrowLimit_; } return newBorrowLimit_; } /////////////////////////////////////////////////////////////////////////// ////////// CALC RATES ///////// /////////////////////////////////////////////////////////////////////////// /// @dev Calculates new borrow rate from utilization for a token /// @param rateData_ rate data packed uint256 from storage for the token /// @param utilization_ totalBorrow / totalSupply. 1e4 = 100% utilization /// @return rate_ rate for that particular token in 1e2 precision (e.g. 5% rate = 500) function calcBorrowRateFromUtilization(uint256 rateData_, uint256 utilization_) internal returns (uint256 rate_) { // extract rate version: 4 bits (0xF) starting from bit 0 uint256 rateVersion_ = (rateData_ & 0xF); if (rateVersion_ == 1) { rate_ = calcRateV1(rateData_, utilization_); } else if (rateVersion_ == 2) { rate_ = calcRateV2(rateData_, utilization_); } else { revert FluidLiquidityCalcsError(ErrorTypes.LiquidityCalcs__UnsupportedRateVersion); } if (rate_ > X16) { // hard cap for borrow rate at maximum value 16 bits (65535) to make sure it does not overflow storage space. // this is unlikely to ever happen if configs stay within expected levels. rate_ = X16; // emit event to more easily become aware emit BorrowRateMaxCap(); } } /// @dev calculates the borrow rate based on utilization for rate data version 1 (with one kink) in 1e2 precision /// @param rateData_ rate data packed uint256 from storage for the token /// @param utilization_ in 1e2 (100% = 1e4) /// @return rate_ rate in 1e2 precision function calcRateV1(uint256 rateData_, uint256 utilization_) internal pure returns (uint256 rate_) { /// For rate v1 (one kink) ------------------------------------------------------ /// Next 16 bits => 4 - 19 => Rate at utilization 0% (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Next 16 bits => 20- 35 => Utilization at kink1 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Next 16 bits => 36- 51 => Rate at utilization kink1 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Next 16 bits => 52- 67 => Rate at utilization 100% (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Last 188 bits => 68-255 => blank, might come in use in future // y = mx + c. // y is borrow rate // x is utilization // m = slope (m can be 0 but never negative) // c is constant (c can be negative) uint256 y1_; uint256 y2_; uint256 x1_; uint256 x2_; // extract kink1: 16 bits (0xFFFF) starting from bit 20 // kink is in 1e2, same as utilization, so no conversion needed for direct comparison of the two uint256 kink1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_UTILIZATION_AT_KINK) & X16; if (utilization_ < kink1_) { // if utilization is less than kink y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_ZERO) & X16; y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_KINK) & X16; x1_ = 0; // 0% x2_ = kink1_; } else { // else utilization is greater than kink y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_KINK) & X16; y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_MAX) & X16; x1_ = kink1_; x2_ = FOUR_DECIMALS; // 100% } int256 constant_; uint256 slope_; unchecked { // calculating slope with twelve decimal precision. m = (y2 - y1) / (x2 - x1). // utilization of x2 can not be <= utilization of x1 (so no underflow or 0 divisor) and rate at y2 can not be < rate at y1 // y is in 1e2 so can not overflow when multiplied with TWELVE_DECIMALS slope_ = ((y2_ - y1_) * TWELVE_DECIMALS) / (x2_ - x1_); // calculating constant at 12 decimal precision. slope is already in 12 decimal hence only multiple with y1. c = y - mx. // maximum y1_ value is 65535. 65535 * 1e12 can not overflow int256 // maximum slope is 65535 - 0 * TWELVE_DECIMALS / 1 = 65535 * 1e12; // maximum x1_ is 100% (9_999 actually) => slope_ * x1_ can not overflow int256 // subtraction most extreme case would be 0 - max value slope_ * x1_ => can not underflow int256 constant_ = int256(y1_ * TWELVE_DECIMALS) - int256(slope_ * x1_); // calculating new borrow rate // - slope_ max value is 65535 * 1e12, // - utilization max value is let's say 500% (extreme case where borrow rate increases borrow amount without new supply) // - constant max value is 65535 * 1e12 // so max values are 65535 * 1e12 * 50_000 + 65535 * 1e12 -> 3.2768*10^21, which easily fits int256 // divisor TWELVE_DECIMALS can not be 0 rate_ = (uint256(int256(slope_ * utilization_) + constant_)) / TWELVE_DECIMALS; } } /// @dev calculates the borrow rate based on utilization for rate data version 2 (with two kinks) in 1e4 precision /// @param rateData_ rate data packed uint256 from storage for the token /// @param utilization_ in 1e2 (100% = 1e4) /// @return rate_ rate in 1e4 precision function calcRateV2(uint256 rateData_, uint256 utilization_) internal pure returns (uint256 rate_) { /// For rate v2 (two kinks) ----------------------------------------------------- /// Next 16 bits => 4 - 19 => Rate at utilization 0% (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Next 16 bits => 20- 35 => Utilization at kink1 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Next 16 bits => 36- 51 => Rate at utilization kink1 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Next 16 bits => 52- 67 => Utilization at kink2 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Next 16 bits => 68- 83 => Rate at utilization kink2 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Next 16 bits => 84- 99 => Rate at utilization 100% (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535) /// Last 156 bits => 100-255 => blank, might come in use in future // y = mx + c. // y is borrow rate // x is utilization // m = slope (m can be 0 but never negative) // c is constant (c can be negative) uint256 y1_; uint256 y2_; uint256 x1_; uint256 x2_; // extract kink1: 16 bits (0xFFFF) starting from bit 20 // kink is in 1e2, same as utilization, so no conversion needed for direct comparison of the two uint256 kink1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_UTILIZATION_AT_KINK1) & X16; if (utilization_ < kink1_) { // if utilization is less than kink1 y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_ZERO) & X16; y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK1) & X16; x1_ = 0; // 0% x2_ = kink1_; } else { // extract kink2: 16 bits (0xFFFF) starting from bit 52 uint256 kink2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_UTILIZATION_AT_KINK2) & X16; if (utilization_ < kink2_) { // if utilization is less than kink2 y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK1) & X16; y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK2) & X16; x1_ = kink1_; x2_ = kink2_; } else { // else utilization is greater than kink2 y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK2) & X16; y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_MAX) & X16; x1_ = kink2_; x2_ = FOUR_DECIMALS; } } int256 constant_; uint256 slope_; unchecked { // calculating slope with twelve decimal precision. m = (y2 - y1) / (x2 - x1). // utilization of x2 can not be <= utilization of x1 (so no underflow or 0 divisor) and rate at y2 can not be < rate at y1 // y is in 1e2 so can not overflow when multiplied with TWELVE_DECIMALS slope_ = ((y2_ - y1_) * TWELVE_DECIMALS) / (x2_ - x1_); // calculating constant at 12 decimal precision. slope is already in 12 decimal hence only multiple with y1. c = y - mx. // maximum y1_ value is 65535. 65535 * 1e12 can not overflow int256 // maximum slope is 65535 - 0 * TWELVE_DECIMALS / 1 = 65535 * 1e12; // maximum x1_ is 100% (9_999 actually) => slope_ * x1_ can not overflow int256 // subtraction most extreme case would be 0 - max value slope_ * x1_ => can not underflow int256 constant_ = int256(y1_ * TWELVE_DECIMALS) - int256(slope_ * x1_); // calculating new borrow rate // - slope_ max value is 65535 * 1e12, // - utilization max value is let's say 500% (extreme case where borrow rate increases borrow amount without new supply) // - constant max value is 65535 * 1e12 // so max values are 65535 * 1e12 * 50_000 + 65535 * 1e12 -> 3.2768*10^21, which easily fits int256 // divisor TWELVE_DECIMALS can not be 0 rate_ = (uint256(int256(slope_ * utilization_) + constant_)) / TWELVE_DECIMALS; } } /// @dev reads the total supply out of Liquidity packed storage `totalAmounts_` for `supplyExchangePrice_` function getTotalSupply( uint256 totalAmounts_, uint256 supplyExchangePrice_ ) internal pure returns (uint256 totalSupply_) { // totalSupply_ => supplyInterestFree totalSupply_ = (totalAmounts_ >> LiquiditySlotsLink.BITS_TOTAL_AMOUNTS_SUPPLY_INTEREST_FREE) & X64; totalSupply_ = (totalSupply_ >> DEFAULT_EXPONENT_SIZE) << (totalSupply_ & DEFAULT_EXPONENT_MASK); uint256 totalSupplyRaw_ = totalAmounts_ & X64; // no shifting as supplyRaw is first 64 bits totalSupplyRaw_ = (totalSupplyRaw_ >> DEFAULT_EXPONENT_SIZE) << (totalSupplyRaw_ & DEFAULT_EXPONENT_MASK); // totalSupply = supplyInterestFree + supplyRawInterest normalized from raw totalSupply_ += ((totalSupplyRaw_ * supplyExchangePrice_) / EXCHANGE_PRICES_PRECISION); } /// @dev reads the total borrow out of Liquidity packed storage `totalAmounts_` for `borrowExchangePrice_` function getTotalBorrow( uint256 totalAmounts_, uint256 borrowExchangePrice_ ) internal pure returns (uint256 totalBorrow_) { // totalBorrow_ => borrowInterestFree // no & mask needed for borrow interest free as it occupies the last bits in the storage slot totalBorrow_ = (totalAmounts_ >> LiquiditySlotsLink.BITS_TOTAL_AMOUNTS_BORROW_INTEREST_FREE); totalBorrow_ = (totalBorrow_ >> DEFAULT_EXPONENT_SIZE) << (totalBorrow_ & DEFAULT_EXPONENT_MASK); uint256 totalBorrowRaw_ = (totalAmounts_ >> LiquiditySlotsLink.BITS_TOTAL_AMOUNTS_BORROW_WITH_INTEREST) & X64; totalBorrowRaw_ = (totalBorrowRaw_ >> DEFAULT_EXPONENT_SIZE) << (totalBorrowRaw_ & DEFAULT_EXPONENT_MASK); // totalBorrow = borrowInterestFree + borrowRawInterest normalized from raw totalBorrow_ += ((totalBorrowRaw_ * borrowExchangePrice_) / EXCHANGE_PRICES_PRECISION); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; /// @notice library that helps in reading / working with storage slot data of Fluid Liquidity. /// @dev as all data for Fluid Liquidity is internal, any data must be fetched directly through manual /// slot reading through this library or, if gas usage is less important, through the FluidLiquidityResolver. library LiquiditySlotsLink { /// @dev storage slot for status at Liquidity uint256 internal constant LIQUIDITY_STATUS_SLOT = 1; /// @dev storage slot for auths mapping at Liquidity uint256 internal constant LIQUIDITY_AUTHS_MAPPING_SLOT = 2; /// @dev storage slot for guardians mapping at Liquidity uint256 internal constant LIQUIDITY_GUARDIANS_MAPPING_SLOT = 3; /// @dev storage slot for user class mapping at Liquidity uint256 internal constant LIQUIDITY_USER_CLASS_MAPPING_SLOT = 4; /// @dev storage slot for exchangePricesAndConfig mapping at Liquidity uint256 internal constant LIQUIDITY_EXCHANGE_PRICES_MAPPING_SLOT = 5; /// @dev storage slot for rateData mapping at Liquidity uint256 internal constant LIQUIDITY_RATE_DATA_MAPPING_SLOT = 6; /// @dev storage slot for totalAmounts mapping at Liquidity uint256 internal constant LIQUIDITY_TOTAL_AMOUNTS_MAPPING_SLOT = 7; /// @dev storage slot for user supply double mapping at Liquidity uint256 internal constant LIQUIDITY_USER_SUPPLY_DOUBLE_MAPPING_SLOT = 8; /// @dev storage slot for user borrow double mapping at Liquidity uint256 internal constant LIQUIDITY_USER_BORROW_DOUBLE_MAPPING_SLOT = 9; /// @dev storage slot for listed tokens array at Liquidity uint256 internal constant LIQUIDITY_LISTED_TOKENS_ARRAY_SLOT = 10; // -------------------------------- // @dev stacked uint256 storage slots bits position data for each: // ExchangePricesAndConfig uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_RATE = 0; uint256 internal constant BITS_EXCHANGE_PRICES_FEE = 16; uint256 internal constant BITS_EXCHANGE_PRICES_UTILIZATION = 30; uint256 internal constant BITS_EXCHANGE_PRICES_UPDATE_THRESHOLD = 44; uint256 internal constant BITS_EXCHANGE_PRICES_LAST_TIMESTAMP = 58; uint256 internal constant BITS_EXCHANGE_PRICES_SUPPLY_EXCHANGE_PRICE = 91; uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_EXCHANGE_PRICE = 155; uint256 internal constant BITS_EXCHANGE_PRICES_SUPPLY_RATIO = 219; uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_RATIO = 234; // RateData: uint256 internal constant BITS_RATE_DATA_VERSION = 0; // RateData: V1 uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_ZERO = 4; uint256 internal constant BITS_RATE_DATA_V1_UTILIZATION_AT_KINK = 20; uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_KINK = 36; uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_MAX = 52; // RateData: V2 uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_ZERO = 4; uint256 internal constant BITS_RATE_DATA_V2_UTILIZATION_AT_KINK1 = 20; uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK1 = 36; uint256 internal constant BITS_RATE_DATA_V2_UTILIZATION_AT_KINK2 = 52; uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK2 = 68; uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_MAX = 84; // TotalAmounts uint256 internal constant BITS_TOTAL_AMOUNTS_SUPPLY_WITH_INTEREST = 0; uint256 internal constant BITS_TOTAL_AMOUNTS_SUPPLY_INTEREST_FREE = 64; uint256 internal constant BITS_TOTAL_AMOUNTS_BORROW_WITH_INTEREST = 128; uint256 internal constant BITS_TOTAL_AMOUNTS_BORROW_INTEREST_FREE = 192; // UserSupplyData uint256 internal constant BITS_USER_SUPPLY_MODE = 0; uint256 internal constant BITS_USER_SUPPLY_AMOUNT = 1; uint256 internal constant BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT = 65; uint256 internal constant BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP = 129; uint256 internal constant BITS_USER_SUPPLY_EXPAND_PERCENT = 162; uint256 internal constant BITS_USER_SUPPLY_EXPAND_DURATION = 176; uint256 internal constant BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT = 200; uint256 internal constant BITS_USER_SUPPLY_IS_PAUSED = 255; // UserBorrowData uint256 internal constant BITS_USER_BORROW_MODE = 0; uint256 internal constant BITS_USER_BORROW_AMOUNT = 1; uint256 internal constant BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT = 65; uint256 internal constant BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP = 129; uint256 internal constant BITS_USER_BORROW_EXPAND_PERCENT = 162; uint256 internal constant BITS_USER_BORROW_EXPAND_DURATION = 176; uint256 internal constant BITS_USER_BORROW_BASE_BORROW_LIMIT = 200; uint256 internal constant BITS_USER_BORROW_MAX_BORROW_LIMIT = 218; uint256 internal constant BITS_USER_BORROW_IS_PAUSED = 255; // -------------------------------- /// @notice Calculating the slot ID for Liquidity contract for single mapping at `slot_` for `key_` function calculateMappingStorageSlot(uint256 slot_, address key_) internal pure returns (bytes32) { return keccak256(abi.encode(key_, slot_)); } /// @notice Calculating the slot ID for Liquidity contract for double mapping at `slot_` for `key1_` and `key2_` function calculateDoubleMappingStorageSlot( uint256 slot_, address key1_, address key2_ ) internal pure returns (bytes32) { bytes32 intermediateSlot_ = keccak256(abi.encode(key1_, slot_)); return keccak256(abi.encode(key2_, intermediateSlot_)); } }
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.21; import { LibsErrorTypes as ErrorTypes } from "./errorTypes.sol"; /// @notice provides minimalistic methods for safe transfers, e.g. ERC20 safeTransferFrom library SafeTransfer { error FluidSafeTransferError(uint256 errorId_); /// @dev Transfer `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. /// Minimally modified from Solmate SafeTransferLib (address as input param for token, Custom Error): /// https://github.com/transmissions11/solmate/blob/50e15bb566f98b7174da9b0066126a4c3e75e0fd/src/utils/SafeTransferLib.sol#L31-L63 function safeTransferFrom(address token_, address from_, address to_, uint256 amount_) internal { bool success_; /// @solidity memory-safe-assembly assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata into memory, beginning with the function selector. mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) mstore(add(freeMemoryPointer, 4), and(from_, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from_" argument. mstore(add(freeMemoryPointer, 36), and(to_, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to_" argument. mstore(add(freeMemoryPointer, 68), amount_) // Append the "amount_" argument. Masking not required as it's a full 32 byte type. success_ := and( // Set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data. or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3. // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. // Counterintuitively, this call must be positioned second to the or() call in the // surrounding and() call or else returndatasize() will be zero during the computation. call(gas(), token_, 0, freeMemoryPointer, 100, 0, 32) ) } if (!success_) { revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFromFailed); } } /// @dev Transfer `amount_` of `token_` to `to_`. /// If `token_` returns no value, non-reverting calls are assumed to be successful. /// Minimally modified from Solmate SafeTransferLib (address as input param for token, Custom Error): /// https://github.com/transmissions11/solmate/blob/50e15bb566f98b7174da9b0066126a4c3e75e0fd/src/utils/SafeTransferLib.sol#L65-L95 function safeTransfer(address token_, address to_, uint256 amount_) internal { bool success_; /// @solidity memory-safe-assembly assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata into memory, beginning with the function selector. mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(freeMemoryPointer, 4), and(to_, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to_" argument. mstore(add(freeMemoryPointer, 36), amount_) // Append the "amount_" argument. Masking not required as it's a full 32 byte type. success_ := and( // Set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data. or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. // Counterintuitively, this call must be positioned second to the or() call in the // surrounding and() call or else returndatasize() will be zero during the computation. call(gas(), token_, 0, freeMemoryPointer, 68, 0, 32) ) } if (!success_) { revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFailed); } } /// @dev Transfer `amount_` of ` native token to `to_`. /// Minimally modified from Solmate SafeTransferLib (Custom Error): /// https://github.com/transmissions11/solmate/blob/50e15bb566f98b7174da9b0066126a4c3e75e0fd/src/utils/SafeTransferLib.sol#L15-L25 function safeTransferNative(address to_, uint256 amount_) internal { bool success_; /// @solidity memory-safe-assembly assembly { // Transfer the ETH and store if it succeeded or not. success_ := call(gas(), to_, amount_, 0, 0, 0, 0) } if (!success_) { revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFailed); } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; abstract contract Structs { struct AddressBool { address addr; bool value; } struct AddressUint256 { address addr; uint256 value; } /// @notice struct to set borrow rate data for version 1 struct RateDataV1Params { /// /// @param token for rate data address token; /// /// @param kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100 /// utilization below kink usually means slow increase in rate, once utilization is above kink borrow rate increases fast uint256 kink; /// /// @param rateAtUtilizationZero desired borrow rate when utilization is zero. in 1e2: 100% = 10_000; 1% = 100 /// i.e. constant minimum borrow rate /// e.g. at utilization = 0.01% rate could still be at least 4% (rateAtUtilizationZero would be 400 then) uint256 rateAtUtilizationZero; /// /// @param rateAtUtilizationKink borrow rate when utilization is at kink. in 1e2: 100% = 10_000; 1% = 100 /// e.g. when rate should be 7% at kink then rateAtUtilizationKink would be 700 uint256 rateAtUtilizationKink; /// /// @param rateAtUtilizationMax borrow rate when utilization is maximum at 100%. in 1e2: 100% = 10_000; 1% = 100 /// e.g. when rate should be 125% at 100% then rateAtUtilizationMax would be 12_500 uint256 rateAtUtilizationMax; } /// @notice struct to set borrow rate data for version 2 struct RateDataV2Params { /// /// @param token for rate data address token; /// /// @param kink1 first kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100 /// utilization below kink 1 usually means slow increase in rate, once utilization is above kink 1 borrow rate increases faster uint256 kink1; /// /// @param kink2 second kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100 /// utilization below kink 2 usually means slow / medium increase in rate, once utilization is above kink 2 borrow rate increases fast uint256 kink2; /// /// @param rateAtUtilizationZero desired borrow rate when utilization is zero. in 1e2: 100% = 10_000; 1% = 100 /// i.e. constant minimum borrow rate /// e.g. at utilization = 0.01% rate could still be at least 4% (rateAtUtilizationZero would be 400 then) uint256 rateAtUtilizationZero; /// /// @param rateAtUtilizationKink1 desired borrow rate when utilization is at first kink. in 1e2: 100% = 10_000; 1% = 100 /// e.g. when rate should be 7% at first kink then rateAtUtilizationKink would be 700 uint256 rateAtUtilizationKink1; /// /// @param rateAtUtilizationKink2 desired borrow rate when utilization is at second kink. in 1e2: 100% = 10_000; 1% = 100 /// e.g. when rate should be 7% at second kink then rateAtUtilizationKink would be 1_200 uint256 rateAtUtilizationKink2; /// /// @param rateAtUtilizationMax desired borrow rate when utilization is maximum at 100%. in 1e2: 100% = 10_000; 1% = 100 /// e.g. when rate should be 125% at 100% then rateAtUtilizationMax would be 12_500 uint256 rateAtUtilizationMax; } /// @notice struct to set token config struct TokenConfig { /// /// @param token address address token; /// /// @param fee charges on borrower's interest. in 1e2: 100% = 10_000; 1% = 100 uint256 fee; /// /// @param threshold on when to update the storage slot. in 1e2: 100% = 10_000; 1% = 100 uint256 threshold; } /// @notice struct to set user supply & withdrawal config struct UserSupplyConfig { /// /// @param user address address user; /// /// @param token address address token; /// /// @param mode: 0 = without interest. 1 = with interest uint8 mode; /// /// @param expandPercent withdrawal limit expand percent. in 1e2: 100% = 10_000; 1% = 100 /// Also used to calculate rate at which withdrawal limit should decrease (instant). uint256 expandPercent; /// /// @param expandDuration withdrawal limit expand duration in seconds. /// used to calculate rate together with expandPercent uint256 expandDuration; /// /// @param baseWithdrawalLimit base limit, below this, user can withdraw the entire amount. /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token: /// with interest -> raw, without interest -> normal uint256 baseWithdrawalLimit; } /// @notice struct to set user borrow & payback config struct UserBorrowConfig { /// /// @param user address address user; /// /// @param token address address token; /// /// @param mode: 0 = without interest. 1 = with interest uint8 mode; /// /// @param expandPercent debt limit expand percent. in 1e2: 100% = 10_000; 1% = 100 /// Also used to calculate rate at which debt limit should decrease (instant). uint256 expandPercent; /// /// @param expandDuration debt limit expand duration in seconds. /// used to calculate rate together with expandPercent uint256 expandDuration; /// /// @param baseDebtCeiling base borrow limit. until here, borrow limit remains as baseDebtCeiling /// (user can borrow until this point at once without stepped expansion). Above this, automated limit comes in place. /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token: /// with interest -> raw, without interest -> normal uint256 baseDebtCeiling; /// /// @param maxDebtCeiling max borrow ceiling, maximum amount the user can borrow. /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token: /// with interest -> raw, without interest -> normal uint256 maxDebtCeiling; } }
//SPDX-License-Identifier: MIT pragma solidity 0.8.21; import { IProxy } from "../../infiniteProxy/interfaces/iProxy.sol"; import { Structs as AdminModuleStructs } from "../adminModule/structs.sol"; interface IFluidLiquidityAdmin { /// @notice adds/removes auths. Auths generally could be contracts which can have restricted actions defined on contract. /// auths can be helpful in reducing governance overhead where it's not needed. /// @param authsStatus_ array of structs setting allowed status for an address. /// status true => add auth, false => remove auth function updateAuths(AdminModuleStructs.AddressBool[] calldata authsStatus_) external; /// @notice adds/removes guardians. Only callable by Governance. /// @param guardiansStatus_ array of structs setting allowed status for an address. /// status true => add guardian, false => remove guardian function updateGuardians(AdminModuleStructs.AddressBool[] calldata guardiansStatus_) external; /// @notice changes the revenue collector address (contract that is sent revenue). Only callable by Governance. /// @param revenueCollector_ new revenue collector address function updateRevenueCollector(address revenueCollector_) external; /// @notice changes current status, e.g. for pausing or unpausing all user operations. Only callable by Auths. /// @param newStatus_ new status /// status = 2 -> pause, status = 1 -> resume. function changeStatus(uint256 newStatus_) external; /// @notice update tokens rate data version 1. Only callable by Auths. /// @param tokensRateData_ array of RateDataV1Params with rate data to set for each token function updateRateDataV1s(AdminModuleStructs.RateDataV1Params[] calldata tokensRateData_) external; /// @notice update tokens rate data version 2. Only callable by Auths. /// @param tokensRateData_ array of RateDataV2Params with rate data to set for each token function updateRateDataV2s(AdminModuleStructs.RateDataV2Params[] calldata tokensRateData_) external; /// @notice updates token configs: fee charge on borrowers interest & storage update utilization threshold. /// Only callable by Auths. /// @param tokenConfigs_ contains token address, fee & utilization threshold function updateTokenConfigs(AdminModuleStructs.TokenConfig[] calldata tokenConfigs_) external; /// @notice updates user classes: 0 is for new protocols, 1 is for established protocols. /// Only callable by Auths. /// @param userClasses_ struct array of uint256 value to assign for each user address function updateUserClasses(AdminModuleStructs.AddressUint256[] calldata userClasses_) external; /// @notice sets user supply configs per token basis. Eg: with interest or interest-free and automated limits. /// Only callable by Auths. /// @param userSupplyConfigs_ struct array containing user supply config, see `UserSupplyConfig` struct for more info function updateUserSupplyConfigs(AdminModuleStructs.UserSupplyConfig[] memory userSupplyConfigs_) external; /// @notice setting user borrow configs per token basis. Eg: with interest or interest-free and automated limits. /// Only callable by Auths. /// @param userBorrowConfigs_ struct array containing user borrow config, see `UserBorrowConfig` struct for more info function updateUserBorrowConfigs(AdminModuleStructs.UserBorrowConfig[] memory userBorrowConfigs_) external; /// @notice pause operations for a particular user in class 0 (class 1 users can't be paused by guardians). /// Only callable by Guardians. /// @param user_ address of user to pause operations for /// @param supplyTokens_ token addresses to pause withdrawals for /// @param borrowTokens_ token addresses to pause borrowings for function pauseUser(address user_, address[] calldata supplyTokens_, address[] calldata borrowTokens_) external; /// @notice unpause operations for a particular user in class 0 (class 1 users can't be paused by guardians). /// Only callable by Guardians. /// @param user_ address of user to unpause operations for /// @param supplyTokens_ token addresses to unpause withdrawals for /// @param borrowTokens_ token addresses to unpause borrowings for function unpauseUser(address user_, address[] calldata supplyTokens_, address[] calldata borrowTokens_) external; /// @notice collects revenue for tokens to configured revenueCollector address. /// @param tokens_ array of tokens to collect revenue for /// @dev Note that this can revert if token balance is < revenueAmount (utilization > 100%) function collectRevenue(address[] calldata tokens_) external; /// @notice gets the current updated exchange prices for n tokens and updates all prices, rates related data in storage. /// @param tokens_ tokens to update exchange prices for /// @return supplyExchangePrices_ new supply rates of overall system for each token /// @return borrowExchangePrices_ new borrow rates of overall system for each token function updateExchangePrices( address[] calldata tokens_ ) external returns (uint256[] memory supplyExchangePrices_, uint256[] memory borrowExchangePrices_); } interface IFluidLiquidityLogic is IFluidLiquidityAdmin { /// @notice Single function which handles supply, withdraw, borrow & payback /// @param token_ address of token (0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native) /// @param supplyAmount_ if +ve then supply, if -ve then withdraw, if 0 then nothing /// @param borrowAmount_ if +ve then borrow, if -ve then payback, if 0 then nothing /// @param withdrawTo_ if withdrawal then to which address /// @param borrowTo_ if borrow then to which address /// @param callbackData_ callback data passed to `liquidityCallback` method of protocol /// @return memVar3_ updated supplyExchangePrice /// @return memVar4_ updated borrowExchangePrice /// @dev to trigger skipping in / out transfers when in&out amounts balance themselves out (gas optimization): /// - supply(+) == borrow(+), withdraw(-) == payback(-). /// - `withdrawTo_` / `borrowTo_` must be msg.sender (protocol) /// - `callbackData_` MUST be encoded so that "from" address is at last 20 bytes (if this optimization is desired), /// also for native token operations where liquidityCallback is not triggered! /// from address must come at last position if there is more data. I.e. encode like: /// abi.encode(otherVar1, otherVar2, FROM_ADDRESS). Note dynamic types used with abi.encode come at the end /// so if dynamic types are needed, you must use abi.encodePacked to ensure the from address is at the end. function operate( address token_, int256 supplyAmount_, int256 borrowAmount_, address withdrawTo_, address borrowTo_, bytes calldata callbackData_ ) external payable returns (uint256 memVar3_, uint256 memVar4_); } interface IFluidLiquidity is IProxy, IFluidLiquidityLogic {}
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; abstract contract Error { error FluidLendingError(uint256 errorId_); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; library ErrorTypes { /***********************************| | fToken | |__________________________________*/ /// @notice thrown when a deposit amount is too small to increase BigMath stored balance in Liquidity. /// precision of BigMath is 1e12, so if token holds 120_000_000_000 USDC, min amount to make a difference would be 0.1 USDC. /// i.e. user would send a very small deposit which mints no shares -> revert uint256 internal constant fToken__DepositInsignificant = 20001; /// @notice thrown when minimum output amount is not reached, e.g. for minimum shares minted (deposit) or /// minimum assets received (redeem) uint256 internal constant fToken__MinAmountOut = 20002; /// @notice thrown when maximum amount is surpassed, e.g. for maximum shares burned (withdraw) or /// maximum assets input (mint) uint256 internal constant fToken__MaxAmount = 20003; /// @notice thrown when invalid params are sent to a method, e.g. zero address uint256 internal constant fToken__InvalidParams = 20004; /// @notice thrown when an unauthorized caller is trying to execute an auth-protected method uint256 internal constant fToken__Unauthorized = 20005; /// @notice thrown when a with permit / signature method is called from msg.sender that is the owner. /// Should call the method without permit instead if msg.sender is the owner. uint256 internal constant fToken__PermitFromOwnerCall = 20006; /// @notice thrown when a reentrancy is detected. uint256 internal constant fToken__Reentrancy = 20007; /// @notice thrown when _tokenExchangePrice overflows type(uint64).max uint256 internal constant fToken__ExchangePriceOverflow = 20008; /// @notice thrown when msg.sender is not rebalancer uint256 internal constant fToken__NotRebalancer = 20009; /// @notice thrown when rebalance is called with msg.value > 0 for non NativeUnderlying fToken uint256 internal constant fToken__NotNativeUnderlying = 20010; /// @notice thrown when the received new liquidity exchange price is of unexpected value (< than the old one) uint256 internal constant fToken__LiquidityExchangePriceUnexpected = 20011; /***********************************| | fToken Native Underlying | |__________________________________*/ /// @notice thrown when native deposit is called but sent along `msg.value` does not cover the deposit amount uint256 internal constant fTokenNativeUnderlying__TransferInsufficient = 21001; /// @notice thrown when a liquidity callback is called for a native token operation uint256 internal constant fTokenNativeUnderlying__UnexpectedLiquidityCallback = 21002; /***********************************| | Lending Factory | |__________________________________*/ /// @notice thrown when a method is called with invalid params uint256 internal constant LendingFactory__InvalidParams = 22001; /// @notice thrown when the provided input param address is zero uint256 internal constant LendingFactory__ZeroAddress = 22002; /// @notice thrown when the token already exists uint256 internal constant LendingFactory__TokenExists = 22003; /// @notice thrown when the fToken has not yet been configured at Liquidity uint256 internal constant LendingFactory__LiquidityNotConfigured = 22004; /// @notice thrown when an unauthorized caller is trying to execute an auth-protected method uint256 internal constant LendingFactory__Unauthorized = 22005; /***********************************| | Lending Rewards Rate Model | |__________________________________*/ /// @notice thrown when invalid params are given as input uint256 internal constant LendingRewardsRateModel__InvalidParams = 23001; /// @notice thrown when calculated rewards rate is exceeding the maximum rate uint256 internal constant LendingRewardsRateModel__MaxRate = 23002; /// @notice thrown when start is called by any other address other than initiator uint256 internal constant LendingRewardsRateModel__NotTheInitiator = 23003; /// @notice thrown when start is called after the rewards are already started uint256 internal constant LendingRewardsRateModel__AlreadyStarted = 23004; /// @notice thrown when the provided input param address is zero uint256 internal constant LendingRewardsRateModel__ZeroAddress = 23005; }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; import { IFluidLendingRewardsRateModel } from "../interfaces/iLendingRewardsRateModel.sol"; abstract contract Events { /// @notice emitted whenever admin updates rewards rate model event LogUpdateRewards(IFluidLendingRewardsRateModel indexed rewardsRateModel); /// @notice emitted whenever rebalance is executed to fund difference between Liquidity deposit and totalAssets() /// as rewards through the rebalancer. event LogRebalance(uint256 assets); /// @notice emitted whenever exchange rates are updated event LogUpdateRates(uint256 tokenExchangePrice, uint256 liquidityExchangePrice); /// @notice emitted whenever funds for a certain `token` are rescued to Liquidity event LogRescueFunds(address indexed token); /// @notice emitted whenever rebalancer address is updated event LogUpdateRebalancer(address indexed rebalancer); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; import { ERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol"; import { FixedPointMathLib } from "solmate/src/utils/FixedPointMathLib.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { IAllowanceTransfer } from "../interfaces/permit2/iAllowanceTransfer.sol"; import { IFluidLendingRewardsRateModel } from "../interfaces/iLendingRewardsRateModel.sol"; import { IFluidLendingFactory } from "../interfaces/iLendingFactory.sol"; import { IFToken, IFTokenAdmin } from "../interfaces/iFToken.sol"; import { LiquidityCalcs } from "../../../libraries/liquidityCalcs.sol"; import { BigMathMinified } from "../../../libraries/bigMathMinified.sol"; import { LiquiditySlotsLink } from "../../../libraries/liquiditySlotsLink.sol"; import { SafeTransfer } from "../../../libraries/safeTransfer.sol"; import { IFluidLiquidity } from "../../../liquidity/interfaces/iLiquidity.sol"; import { Variables } from "./variables.sol"; import { Events } from "./events.sol"; import { ErrorTypes } from "../errorTypes.sol"; import { Error } from "../error.sol"; /// @dev ReentrancyGuard based on OpenZeppelin implementation. /// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.8/contracts/security/ReentrancyGuard.sol abstract contract ReentrancyGuard is Error, Variables { uint8 internal constant REENTRANCY_NOT_ENTERED = 1; uint8 internal constant REENTRANCY_ENTERED = 2; constructor() { _status = REENTRANCY_NOT_ENTERED; } /// @dev checks that no reentrancy occurs, reverts if so. Calling the method in the modifier reduces /// bytecode size as modifiers are inlined into bytecode function _checkReentrancy() internal { // On the first call to nonReentrant, _status will be NOT_ENTERED if (_status != REENTRANCY_NOT_ENTERED) { revert FluidLendingError(ErrorTypes.fToken__Reentrancy); } // Any calls to nonReentrant after this point will fail _status = REENTRANCY_ENTERED; } /// @dev Prevents a contract from calling itself, directly or indirectly. /// See OpenZeppelin implementation for more info modifier nonReentrant() { _checkReentrancy(); _; // storing original value triggers a refund (see https://eips.ethereum.org/EIPS/eip-2200) _status = REENTRANCY_NOT_ENTERED; } } /// @dev internal methods for fToken contracts abstract contract fTokenCore is Error, IERC4626, IFToken, Variables, Events, ReentrancyGuard { using FixedPointMathLib for uint256; /// @dev Gets current (updated) Liquidity supply exchange price for the underyling asset function _getLiquidityExchangePrice() internal view returns (uint256 supplyExchangePrice_) { (supplyExchangePrice_, ) = LiquidityCalcs.calcExchangePrices( LIQUIDITY.readFromStorage(LIQUIDITY_EXCHANGE_PRICES_SLOT) ); } /// @dev Gets current Liquidity supply balance of `address(this)` for the underyling asset function _getLiquidityBalance() internal view returns (uint256 balance_) { // extract user supply amount uint256 userSupplyRaw_ = BigMathMinified.fromBigNumber( (LIQUIDITY.readFromStorage(LIQUIDITY_USER_SUPPLY_SLOT) >> LiquiditySlotsLink.BITS_USER_SUPPLY_AMOUNT) & LiquidityCalcs.X64, LiquidityCalcs.DEFAULT_EXPONENT_SIZE, LiquidityCalcs.DEFAULT_EXPONENT_MASK ); unchecked { // can not overflow as userSupplyRaw_ can be maximally type(int128).max, liquidity exchange price type(uint64).max return (userSupplyRaw_ * _getLiquidityExchangePrice()) / EXCHANGE_PRICES_PRECISION; } } /// @dev Gets current Liquidity underlying token balance function _getLiquidityUnderlyingBalance() internal view virtual returns (uint256) { return ASSET.balanceOf(address(LIQUIDITY)); } /// @dev Gets current withdrawable amount at Liquidity `withdrawalLimit_` (withdrawal limit or balance). function _getLiquidityWithdrawable() internal view returns (uint256 withdrawalLimit_) { uint256 userSupplyData_ = LIQUIDITY.readFromStorage(LIQUIDITY_USER_SUPPLY_SLOT); uint256 userSupply_ = BigMathMinified.fromBigNumber( (userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_AMOUNT) & LiquidityCalcs.X64, LiquidityCalcs.DEFAULT_EXPONENT_SIZE, LiquidityCalcs.DEFAULT_EXPONENT_MASK ); withdrawalLimit_ = LiquidityCalcs.calcWithdrawalLimitBeforeOperate(userSupplyData_, userSupply_); // convert raw amounts to normal amounts unchecked { // can not overflow as userSupply_ can be maximally type(int128).max // and withdrawalLimit is smaller than userSupply_ uint256 liquidityExchangePrice_ = _getLiquidityExchangePrice(); withdrawalLimit_ = (withdrawalLimit_ * liquidityExchangePrice_) / EXCHANGE_PRICES_PRECISION; userSupply_ = (userSupply_ * liquidityExchangePrice_) / EXCHANGE_PRICES_PRECISION; } withdrawalLimit_ = userSupply_ > withdrawalLimit_ ? userSupply_ - withdrawalLimit_ : 0; uint256 balanceAtLiquidity_ = _getLiquidityUnderlyingBalance(); return balanceAtLiquidity_ > withdrawalLimit_ ? withdrawalLimit_ : balanceAtLiquidity_; } /// @dev Calculates new token exchange price based on the current liquidity exchange price `newLiquidityExchangePrice_` and rewards rate. /// @param newLiquidityExchangePrice_ new (current) liquidity exchange price function _calculateNewTokenExchangePrice( uint256 newLiquidityExchangePrice_ ) internal view returns (uint256 newTokenExchangePrice_, bool rewardsEnded_) { uint256 oldTokenExchangePrice_ = _tokenExchangePrice; uint256 oldLiquidityExchangePrice_ = _liquidityExchangePrice; if (newLiquidityExchangePrice_ < oldLiquidityExchangePrice_) { // liquidity exchange price should only ever increase. If not, something went wrong and avoid // proceeding with unknown outcome. revert FluidLendingError(ErrorTypes.fToken__LiquidityExchangePriceUnexpected); } uint256 totalReturnInPercent_; // rewardsRateInPercent + liquidityReturnInPercent if (_rewardsActive) { { // get rewards rate per year // only trigger call to rewardsRateModel if rewards are actually active to save gas uint256 rewardsRate_; uint256 rewardsStartTime_; (rewardsRate_, rewardsEnded_, rewardsStartTime_) = _rewardsRateModel.getRate( // use old tokenExchangeRate to calculate the total assets input for the rewards rate (oldTokenExchangePrice_ * totalSupply()) / EXCHANGE_PRICES_PRECISION ); if (rewardsRate_ > MAX_REWARDS_RATE || rewardsEnded_) { // rewardsRate is capped, if it is bigger > MAX_REWARDS_RATE, then the rewardsRateModel // is configured wrongly (which should not be possible). Setting rewards to 0 in that case here. rewardsRate_ = 0; } uint256 lastUpdateTimestamp_ = _lastUpdateTimestamp; if (lastUpdateTimestamp_ < rewardsStartTime_) { // if last update was before the rewards started, make sure rewards actually only accrue // from the actual rewards start time, not from the last update timestamp to avoid overpayment. lastUpdateTimestamp_ = rewardsStartTime_; // Note: overpayment for block.timestamp being > rewards end time does not happen because // rewardsRate_ is forced 0 then. } // calculate rewards return in percent: (rewards_rate * time passed) / seconds_in_a_year. unchecked { // rewardsRate * timeElapsed / SECONDS_PER_YEAR. // no safe checks needed here because timeElapsed can not underflow, // rewardsRate is in 1e12 at max value being MAX_REWARDS_RATE = 25e12 // max value would be 25e12 * 8589934591 / 31536000 (with buffers) = 6.8e15 totalReturnInPercent_ = (rewardsRate_ * (block.timestamp - lastUpdateTimestamp_)) / SECONDS_PER_YEAR; } } } unchecked { // calculate liquidityReturnInPercent: (newLiquidityExchangePrice_ - oldLiquidityExchangePrice_) / oldLiquidityExchangePrice_. // and add it to totalReturnInPercent_ that already holds rewardsRateInPercent_. // max value (in absolute extreme unrealistic case) would be: 6.8e15 + (((max uint64 - 1e12) * 1e12) / 1e12) = 1.845e19 // oldLiquidityExchangePrice_ can not be 0, minimal value is 1e12. subtraction can not underflow because new exchange price // can only be >= oldLiquidityExchangePrice_. totalReturnInPercent_ += ((newLiquidityExchangePrice_ - oldLiquidityExchangePrice_) * 1e14) / oldLiquidityExchangePrice_; } // newTokenExchangePrice_ = oldTokenExchangePrice_ + oldTokenExchangePrice_ * totalReturnInPercent_ newTokenExchangePrice_ = oldTokenExchangePrice_ + ((oldTokenExchangePrice_ * totalReturnInPercent_) / 1e14); // divided by 100% (1e14) } /// @dev calculates new exchange prices, updates values in storage and returns new tokenExchangePrice (with reward rates) function _updateRates( uint256 liquidityExchangePrice_, bool forceUpdateStorage_ ) internal returns (uint256 tokenExchangePrice_) { bool rewardsEnded_; (tokenExchangePrice_, rewardsEnded_) = _calculateNewTokenExchangePrice(liquidityExchangePrice_); if (_rewardsActive || forceUpdateStorage_) { // Solidity will NOT cause a revert if values are too big to fit max uint type size. Explicitly check before // writing to storage. Also see https://github.com/ethereum/solidity/issues/10195. if (tokenExchangePrice_ > type(uint64).max) { revert FluidLendingError(ErrorTypes.fToken__ExchangePriceOverflow); } _tokenExchangePrice = uint64(tokenExchangePrice_); _liquidityExchangePrice = uint64(liquidityExchangePrice_); _lastUpdateTimestamp = uint40(block.timestamp); emit LogUpdateRates(tokenExchangePrice_, liquidityExchangePrice_); } if (rewardsEnded_) { // set rewardsActive flag to false to save gas for all future exchange prices calculations, // without having to explicitly require setting `updateRewards` to address zero. // Note that it would be fine that even the current tx does not update exchange prices in storage, // because if rewardsEnded_ is true, rewardsRate_ must be 0, so the only yield is from LIQUIDITY. // But to be extra safe, writing to storage in that one case too before setting _rewardsActive to false. _rewardsActive = false; } return tokenExchangePrice_; } /// @dev splits a bytes signature `sig` into `v`, `r`, `s`. /// Taken from https://docs.soliditylang.org/en/v0.8.17/solidity-by-example.html function _splitSignature(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s) { require(sig.length == 65); assembly { // first 32 bytes, after the length prefix. r := mload(add(sig, 32)) // second 32 bytes. s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes). v := byte(0, mload(add(sig, 96))) } return (v, r, s); } /// @dev Deposit `assets_` amount of tokens to Liquidity /// @param assets_ The amount of tokens to deposit /// @param liquidityCallbackData_ callback data passed to Liquidity for `liquidityCallback` /// @return exchangePrice_ liquidity exchange price for token function _depositToLiquidity( uint256 assets_, bytes memory liquidityCallbackData_ ) internal virtual returns (uint256 exchangePrice_) { // @dev Note: Although there might be some small difference between the `assets_` amount and the actual amount // accredited at Liquidity due to BigMath rounding down, this amount is so small that it can be ignored. // because of BigMath precision of 7.2057594e16 for a coefficient size of 56, it would require >72 trillion DAI // to "benefit" 1 DAI in additional shares minted. Considering gas cost + APR per second, this ensures such // a manipulation attempt becomes extremely unlikely. // send funds to Liquidity protocol to generate yield (exchangePrice_, ) = LIQUIDITY.operate( address(ASSET), SafeCast.toInt256(assets_), 0, address(0), address(0), liquidityCallbackData_ // callback data. -> "from" for transferFrom in `liquidityCallback` ); } /// @dev Withdraw `assets_` amount of tokens from Liquidity directly to `receiver_` /// @param assets_ The amount of tokens to withdraw /// @param receiver_ the receiver address of withdraw amount /// @return exchangePrice_ liquidity exchange price for token function _withdrawFromLiquidity( uint256 assets_, address receiver_ ) internal virtual returns (uint256 exchangePrice_) { // @dev See similar comment in `_depositToLiquidity()` regarding burning a tiny bit of additional shares here // because of inaccuracies in Liquidity userSupply BigMath being rounded down. // get funds back from Liquidity protocol to send to the user (exchangePrice_, ) = LIQUIDITY.operate( address(ASSET), -SafeCast.toInt256(assets_), 0, receiver_, address(0), new bytes(0) // callback data -> withdraw doesn't trigger a callback ); } /// @dev deposits `assets_` into liquidity and mints shares for `receiver_`. Returns amount of `sharesMinted_`. function _executeDeposit( uint256 assets_, address receiver_, bytes memory liquidityCallbackData_ ) internal virtual validAddress(receiver_) returns (uint256 sharesMinted_) { // send funds to Liquidity protocol to generate yield -> returns updated liquidityExchangePrice uint256 tokenExchangePrice_ = _depositToLiquidity(assets_, liquidityCallbackData_); // update the exchange prices tokenExchangePrice_ = _updateRates(tokenExchangePrice_, false); // calculate the shares to mint // not using previewDeposit here because we just got newTokenExchangePrice_ sharesMinted_ = (assets_ * EXCHANGE_PRICES_PRECISION) / tokenExchangePrice_; if (sharesMinted_ == 0) { revert FluidLendingError(ErrorTypes.fToken__DepositInsignificant); } _mint(receiver_, sharesMinted_); emit Deposit(msg.sender, receiver_, assets_, sharesMinted_); } /// @dev withdraws `assets_` from liquidity to `receiver_` and burns shares from `owner_`. /// Returns amount of `sharesBurned_`. /// requires nonReentrant! modifier on calling method otherwise ERC777s could reenter! function _executeWithdraw( uint256 assets_, address receiver_, address owner_ ) internal virtual validAddress(receiver_) returns (uint256 sharesBurned_) { // burn shares for assets_ amount: assets_ * EXCHANGE_PRICES_PRECISION / updatedTokenTexchangePrice. Rounded up. // Note to be extra safe we do the shares burn before the withdrawFromLiquidity, even though that would return the // updated liquidityExchangePrice and thus save gas. sharesBurned_ = assets_.mulDivUp(EXCHANGE_PRICES_PRECISION, _updateRates(_getLiquidityExchangePrice(), false)); /* The `mulDivUp` function is designed to round up the result of multiplication followed by division. Given non-zero `assets_` and the rounding-up behavior of this function, `sharesBurned_` will always be at least 1 if there's any remainder in the division. Thus, if `assets_` is non-zero, `sharesBurned_` can never be 0. The nature of the function ensures that even the smallest fractional result (greater than 0) will be rounded up to 1. Hence, there's no need to check for a rounding error that results in 0. Furthermore, if `assets_` was 0, an error 'UserModule__OperateAmountsZero' would already have been thrown during the `operate` function, ensuring the contract never reaches this point with a zero `assets_` value. Note: If ever the logic or the function behavior changes in the future, this assertion may need to be reconsidered. */ _burn(owner_, sharesBurned_); // withdraw from liquidity directly to _receiver. _withdrawFromLiquidity(assets_, receiver_); emit Withdraw(msg.sender, receiver_, owner_, assets_, sharesBurned_); } } /// @notice fToken view methods. Implements view methods for ERC4626 compatibility abstract contract fTokenViews is fTokenCore { using FixedPointMathLib for uint256; /// @inheritdoc IFToken function getData() public view returns ( IFluidLiquidity liquidity_, IFluidLendingFactory lendingFactory_, IFluidLendingRewardsRateModel lendingRewardsRateModel_, IAllowanceTransfer permit2_, address rebalancer_, bool rewardsActive_, uint256 liquidityBalance_, uint256 liquidityExchangePrice_, uint256 tokenExchangePrice_ ) { liquidityExchangePrice_ = _getLiquidityExchangePrice(); bool rewardsEnded_; (tokenExchangePrice_, rewardsEnded_) = _calculateNewTokenExchangePrice(liquidityExchangePrice_); return ( LIQUIDITY, LENDING_FACTORY, _rewardsRateModel, PERMIT2, _rebalancer, _rewardsActive && !rewardsEnded_, _getLiquidityBalance(), liquidityExchangePrice_, tokenExchangePrice_ ); } /// @inheritdoc IERC4626 function asset() public view virtual override returns (address) { return address(ASSET); } /// @inheritdoc IERC4626 function totalAssets() public view virtual override returns (uint256) { (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice()); return // all the underlying tokens are stored in Liquidity contract at all times (tokenExchangePrice_ * totalSupply()) / EXCHANGE_PRICES_PRECISION; } /// @inheritdoc IERC4626 function convertToShares(uint256 assets_) public view virtual override returns (uint256) { (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice()); return assets_.mulDivDown(EXCHANGE_PRICES_PRECISION, tokenExchangePrice_); } /// @inheritdoc IERC4626 function convertToAssets(uint256 shares_) public view virtual override returns (uint256) { (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice()); return shares_.mulDivDown(tokenExchangePrice_, EXCHANGE_PRICES_PRECISION); } /// @inheritdoc IERC4626 /// @notice returned amount might be slightly different from actual amount at execution. function previewDeposit(uint256 assets_) public view virtual override returns (uint256) { return convertToShares(assets_); } /// @inheritdoc IERC4626 function previewMint(uint256 shares_) public view virtual override returns (uint256) { (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice()); return shares_.mulDivUp(tokenExchangePrice_, EXCHANGE_PRICES_PRECISION); } /// @inheritdoc IERC4626 function previewWithdraw(uint256 assets_) public view virtual override returns (uint256) { (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice()); return assets_.mulDivUp(EXCHANGE_PRICES_PRECISION, tokenExchangePrice_); } /// @inheritdoc IERC4626 /// @notice returned amount might be slightly different from actual amount at execution. function previewRedeem(uint256 shares_) public view virtual override returns (uint256) { return convertToAssets(shares_); } /*////////////////////////////////////////////////////////////// DEPOSIT/WITHDRAWAL LIMIT LOGIC //////////////////////////////////////////////////////////////*/ /// @inheritdoc IERC4626 function maxDeposit(address) public view virtual override returns (uint256) { // read total supplyInterest_ for the token at Liquidity and convert from BigMath uint256 supplyInterest_ = LIQUIDITY.readFromStorage(LIQUIDITY_TOTAL_AMOUNTS_SLOT) & LiquidityCalcs.X64; supplyInterest_ = (supplyInterest_ >> LiquidityCalcs.DEFAULT_EXPONENT_SIZE) << (supplyInterest_ & LiquidityCalcs.DEFAULT_EXPONENT_MASK); unchecked { // normalize from raw supplyInterest_ = (supplyInterest_ * _getLiquidityExchangePrice()) / EXCHANGE_PRICES_PRECISION; // compare against hardcoded max possible value for total supply considering BigMath rounding down: // type(int128).max) after BigMath rounding (first 56 bits precision, then 71 bits getting set to 0) // so 1111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000000000 // = 170141183460469229370504062281061498880. using minus 1 if (supplyInterest_ > 170141183460469229370504062281061498879) { return 0; } // type(int128).max is the maximum interactable amount at Liquidity. But also total token amounts // must not overflow type(int128).max, so max depositable is type(int128).max - totalSupply. return uint256(uint128(type(int128).max)) - supplyInterest_; } } /// @inheritdoc IERC4626 function maxMint(address) public view virtual override returns (uint256) { return convertToShares(maxDeposit(address(0))); } /// @inheritdoc IERC4626 function maxWithdraw(address owner_) public view virtual override returns (uint256) { uint256 maxWithdrawableAtLiquidity_ = _getLiquidityWithdrawable(); uint256 ownerBalance_ = convertToAssets(balanceOf(owner_)); return maxWithdrawableAtLiquidity_ < ownerBalance_ ? maxWithdrawableAtLiquidity_ : ownerBalance_; } /// @inheritdoc IERC4626 function maxRedeem(address owner_) public view virtual override returns (uint256) { uint256 maxWithdrawableAtLiquidity_ = convertToShares(_getLiquidityWithdrawable()); uint256 ownerBalance_ = balanceOf(owner_); return maxWithdrawableAtLiquidity_ < ownerBalance_ ? maxWithdrawableAtLiquidity_ : ownerBalance_; } /// @inheritdoc IFToken function minDeposit() public view returns (uint256) { uint256 minBigMathRounding_ = 1 << (LIQUIDITY.readFromStorage(LIQUIDITY_TOTAL_AMOUNTS_SLOT) & LiquidityCalcs.DEFAULT_EXPONENT_MASK); // 1 << total supply exponent uint256 previewMint_ = previewMint(1); // rounds up return minBigMathRounding_ > previewMint_ ? minBigMathRounding_ : previewMint_; } } /// @notice fToken admin related methods. fToken admins are Lending Factory auths. Possible actions are /// updating rewards, funding rewards, and rescuing any stuck funds (fToken contract itself never holds any funds). abstract contract fTokenAdmin is fTokenCore, fTokenViews { /// @dev checks if `msg.sender` is an allowed auth at LendingFactory. internal method instead of modifier /// to reduce bytecode size. function _checkIsLendingFactoryAuth() internal view { if (!LENDING_FACTORY.isAuth(msg.sender)) { revert FluidLendingError(ErrorTypes.fToken__Unauthorized); } } /// @inheritdoc IFTokenAdmin function updateRewards(IFluidLendingRewardsRateModel rewardsRateModel_) external { _checkIsLendingFactoryAuth(); // @dev no check for address zero needed here, as that is actually explicitly checked where _rewardsRateModel // is used. In fact it is beneficial to set _rewardsRateModel to address zero when there are no rewards. // apply current rewards rate before updating to new one updateRates(); _rewardsRateModel = rewardsRateModel_; // set flag _rewardsActive _rewardsActive = address(rewardsRateModel_) != address(0); emit LogUpdateRewards(rewardsRateModel_); } /// @inheritdoc IFTokenAdmin function rebalance() external payable virtual nonReentrant returns (uint256 assets_) { if (msg.sender != _rebalancer) { revert FluidLendingError(ErrorTypes.fToken__NotRebalancer); } if (msg.value > 0) { revert FluidLendingError(ErrorTypes.fToken__NotNativeUnderlying); } // calculating difference in assets. if liquidity balance is bigger it'll throw which is an expected behaviour assets_ = totalAssets() - _getLiquidityBalance(); // send funds to Liquidity protocol uint256 liquidityExchangePrice_ = _depositToLiquidity(assets_, abi.encode(msg.sender)); // update the exchange prices, always updating on storage _updateRates(liquidityExchangePrice_, true); // no shares are minted when funding fToken contract for rewards emit LogRebalance(assets_); } /// @inheritdoc IFTokenAdmin function updateRebalancer(address newRebalancer_) public validAddress(newRebalancer_) { _checkIsLendingFactoryAuth(); _rebalancer = newRebalancer_; emit LogUpdateRebalancer(newRebalancer_); } /// @inheritdoc IFTokenAdmin function updateRates() public returns (uint256 tokenExchangePrice_, uint256 liquidityExchangePrice_) { liquidityExchangePrice_ = _getLiquidityExchangePrice(); tokenExchangePrice_ = _updateRates(liquidityExchangePrice_, true); } /// @inheritdoc IFTokenAdmin // // @dev this contract never holds any funds: // -> deposited funds are directly sent to Liquidity. // -> rewards are also stored at Liquidity. function rescueFunds(address token_) external virtual nonReentrant { _checkIsLendingFactoryAuth(); SafeTransfer.safeTransfer(address(token_), address(LIQUIDITY), IERC20(token_).balanceOf(address(this))); emit LogRescueFunds(token_); } } /// @notice fToken public executable actions: deposit, mint, mithdraw and redeem. /// All actions are optionally also available with an additional param to limit the maximum slippage, e.g. maximum /// assets used for minting x amount of shares. abstract contract fTokenActions is fTokenCore, fTokenViews { /// @dev reverts if `amount_` is < `minAmountOut_`. Used to reduce bytecode size. function _revertIfBelowMinAmountOut(uint256 amount_, uint256 minAmountOut_) internal pure { if (amount_ < minAmountOut_) { revert FluidLendingError(ErrorTypes.fToken__MinAmountOut); } } /// @dev reverts if `amount_` is > `maxAmount_`. Used to reduce bytecode size. function _revertIfAboveMaxAmount(uint256 amount_, uint256 maxAmount_) internal pure { if (amount_ > maxAmount_) { revert FluidLendingError(ErrorTypes.fToken__MaxAmount); } } /*////////////////////////////////////////////////////////////// DEPOSIT //////////////////////////////////////////////////////////////*/ /// @inheritdoc IERC4626 /// @notice If `assets_` equals uint256.max then the whole balance of `msg.sender` is deposited. /// `assets_` must at least be `minDeposit()` amount; reverts `fToken__DepositInsignificant()` if not. /// Recommended to use `deposit()` with a `minAmountOut_` param instead to set acceptable limit. /// @return shares_ actually minted shares function deposit( uint256 assets_, address receiver_ ) public virtual override nonReentrant returns (uint256 shares_) { if (assets_ == type(uint256).max) { assets_ = ASSET.balanceOf(msg.sender); } // @dev transfer of tokens from `msg.sender` to liquidity contract happens via `liquidityCallback` shares_ = _executeDeposit(assets_, receiver_, abi.encode(msg.sender)); } /// @notice same as {fToken-deposit} but with an additional setting for minimum output amount. /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of shares is not reached function deposit(uint256 assets_, address receiver_, uint256 minAmountOut_) external returns (uint256 shares_) { shares_ = deposit(assets_, receiver_); _revertIfBelowMinAmountOut(shares_, minAmountOut_); } /*////////////////////////////////////////////////////////////// MINT //////////////////////////////////////////////////////////////*/ /// @inheritdoc IERC4626 /// @notice If `shares_` equals uint256.max then the whole balance of `msg.sender` is deposited. /// `shares_` must at least be `minMint()` amount; reverts `fToken__DepositInsignificant()` if not. /// Note there might be tiny inaccuracies between requested `shares_` and actually received shares amount. /// Recommended to use `deposit()` over mint because it is more gas efficient and less likely to revert. /// Recommended to use `mint()` with a `minAmountOut_` param instead to set acceptable limit. /// @return assets_ deposited assets amount function mint(uint256 shares_, address receiver_) public virtual override nonReentrant returns (uint256 assets_) { if (shares_ == type(uint256).max) { assets_ = ASSET.balanceOf(msg.sender); } else { // No need to check for rounding error, previewMint rounds up. assets_ = previewMint(shares_); } // @dev transfer of tokens from `msg.sender` to liquidity contract happens via `liquidityCallback` _executeDeposit(assets_, receiver_, abi.encode(msg.sender)); } /// @notice same as {fToken-mint} but with an additional setting for maximum assets input amount. /// reverts with `fToken__MaxAmount()` if `maxAssets_` of assets is surpassed to mint `shares_`. function mint(uint256 shares_, address receiver_, uint256 maxAssets_) external returns (uint256 assets_) { assets_ = mint(shares_, receiver_); _revertIfAboveMaxAmount(assets_, maxAssets_); } /*////////////////////////////////////////////////////////////// WITHDRAW //////////////////////////////////////////////////////////////*/ /// @inheritdoc IERC4626 /// @notice If `assets_` equals uint256.max then the whole fToken balance of `owner_` is withdrawn. This does not /// consider withdrawal limit at Liquidity so best to check with `maxWithdraw()` before. /// Note there might be tiny inaccuracies between requested `assets_` and actually received assets amount. /// Recommended to use `withdraw()` with a `minAmountOut_` param instead to set acceptable limit. /// @return shares_ burned shares function withdraw( uint256 assets_, address receiver_, address owner_ ) public virtual override nonReentrant returns (uint256 shares_) { if (assets_ == type(uint256).max) { assets_ = previewRedeem(balanceOf(owner_)); } shares_ = _executeWithdraw(assets_, receiver_, owner_); if (msg.sender != owner_) { _spendAllowance(owner_, msg.sender, shares_); } } /// @notice same as {fToken-withdraw} but with an additional setting for maximum shares burned. /// reverts with `fToken__MaxAmount()` if `maxSharesBurn_` of shares burned is surpassed. function withdraw( uint256 assets_, address receiver_, address owner_, uint256 maxSharesBurn_ ) external returns (uint256 shares_) { shares_ = withdraw(assets_, receiver_, owner_); _revertIfAboveMaxAmount(shares_, maxSharesBurn_); } /*////////////////////////////////////////////////////////////// REDEEM //////////////////////////////////////////////////////////////*/ /// @inheritdoc IERC4626 /// @notice If `shares_` equals uint256.max then the whole balance of `owner_` is withdrawn.This does not /// consider withdrawal limit at Liquidity so best to check with `maxRedeem()` before. /// Recommended to use `withdraw()` over redeem because it is more gas efficient and can set specific amount. /// Recommended to use `redeem()` with a `minAmountOut_` param instead to set acceptable limit. /// @return assets_ withdrawn assets amount function redeem( uint256 shares_, address receiver_, address owner_ ) public virtual override nonReentrant returns (uint256 assets_) { if (shares_ == type(uint256).max) { shares_ = balanceOf(owner_); } assets_ = previewRedeem(shares_); uint256 burnedShares_ = _executeWithdraw(assets_, receiver_, owner_); if (msg.sender != owner_) { _spendAllowance(owner_, msg.sender, burnedShares_); } } /// @notice same as {fToken-redeem} but with an additional setting for minimum output amount. /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of assets is not reached. function redeem( uint256 shares_, address receiver_, address owner_, uint256 minAmountOut_ ) external returns (uint256 assets_) { assets_ = redeem(shares_, receiver_, owner_); _revertIfBelowMinAmountOut(assets_, minAmountOut_); } } /// @notice fTokens support EIP-2612 permit approvals via signature so this contract implements /// withdrawals (withdraw / redeem) with signature used for approval of the fToken shares. abstract contract fTokenEIP2612Withdrawals is fTokenActions { /// @dev creates `sharesToPermit_` allowance for `owner_` via EIP2612 `deadline_` and `signature_` function _allowViaPermitEIP2612( address owner_, uint256 sharesToPermit_, uint256 deadline_, bytes calldata signature_ ) internal { (uint8 v_, bytes32 r_, bytes32 s_) = _splitSignature(signature_); // spender = msg.sender permit(owner_, msg.sender, sharesToPermit_, deadline_, v_, r_, s_); } /// @notice withdraw amount of `assets_` with ERC-2612 permit signature for fToken approval. /// `owner_` signs ERC-2612 permit `signature_` to give allowance of fTokens to `msg.sender`. /// Note there might be tiny inaccuracies between requested `assets_` and actually received assets amount. /// allowance via signature (`sharesToPermit_`) should cover `previewWithdraw(assets_)` plus a little buffer to avoid revert. /// Inherent trust assumption that `msg.sender` will set `receiver_` and `maxSharesBurn_` as `owner_` intends /// (which is always the case when giving allowance to some spender). /// @param sharesToPermit_ shares amount to use for EIP2612 permit(). Should cover `previewWithdraw(assets_)` + small buffer. /// @param assets_ amount of assets to withdraw /// @param receiver_ receiver of withdrawn assets /// @param owner_ owner to withdraw from (must be signature signer) /// @param maxSharesBurn_ maximum accepted amount of shares burned /// @param deadline_ deadline for signature validity /// @param signature_ packed signature of signing the EIP712 hash for ERC-2612 permit /// @return shares_ burned shares amount function withdrawWithSignature( uint256 sharesToPermit_, uint256 assets_, address receiver_, address owner_, uint256 maxSharesBurn_, uint256 deadline_, bytes calldata signature_ ) external virtual nonReentrant returns (uint256 shares_) { if (msg.sender == owner_) { // no sense in operating with permit if msg.sender is owner. should call normal `withdraw()` instead. revert FluidLendingError(ErrorTypes.fToken__PermitFromOwnerCall); } // create allowance through signature_ _allowViaPermitEIP2612(owner_, sharesToPermit_, deadline_, signature_); // execute withdraw to get shares_ to spend amount shares_ = _executeWithdraw(assets_, receiver_, owner_); _revertIfAboveMaxAmount(shares_, maxSharesBurn_); _spendAllowance(owner_, msg.sender, shares_); } /// @notice redeem amount of `shares_` with ERC-2612 permit signature for fToken approval. /// `owner_` signs ERC-2612 permit `signature_` to give allowance of fTokens to `msg.sender`. /// Note there might be tiny inaccuracies between requested `shares_` to redeem and actually burned shares. /// allowance via signature must cover `shares_` plus a tiny buffer. /// Inherent trust assumption that `msg.sender` will set `receiver_` and `minAmountOut_` as `owner_` intends /// (which is always the case when giving allowance to some spender). /// Recommended to use `withdraw()` over redeem because it is more gas efficient and can set specific amount. /// @param shares_ amount of shares to redeem /// @param receiver_ receiver of withdrawn assets /// @param owner_ owner to withdraw from (must be signature signer) /// @param minAmountOut_ minimum accepted amount of assets withdrawn /// @param deadline_ deadline for signature validity /// @param signature_ packed signature of signing the EIP712 hash for ERC-2612 permit /// @return assets_ withdrawn assets amount function redeemWithSignature( uint256 shares_, address receiver_, address owner_, uint256 minAmountOut_, uint256 deadline_, bytes calldata signature_ ) external virtual nonReentrant returns (uint256 assets_) { if (msg.sender == owner_) { // no sense in operating with permit if msg.sender is owner. should call normal `redeem()` instead. revert FluidLendingError(ErrorTypes.fToken__PermitFromOwnerCall); } assets_ = previewRedeem(shares_); _revertIfBelowMinAmountOut(assets_, minAmountOut_); // create allowance through signature_ _allowViaPermitEIP2612(owner_, shares_, deadline_, signature_); // execute withdraw to get actual shares to spend amount uint256 sharesToSpend_ = _executeWithdraw(assets_, receiver_, owner_); _spendAllowance(owner_, msg.sender, sharesToSpend_); } } /// @notice implements fTokens support for deposit / mint via EIP-2612 permit. /// @dev methods revert if underlying asset does not support EIP-2612. abstract contract fTokenEIP2612Deposits is fTokenActions { /// @notice deposit `assets_` amount with EIP-2612 Permit2 signature for underlying asset approval. /// IMPORTANT: This will revert if the underlying `asset()` does not support EIP-2612. /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of shares is not reached. /// `assets_` must at least be `minDeposit()` amount; reverts `fToken__DepositInsignificant()` if not. /// @param assets_ amount of assets to deposit /// @param receiver_ receiver of minted fToken shares /// @param minAmountOut_ minimum accepted amount of shares minted /// @param deadline_ deadline for signature validity /// @param signature_ packed signature of signing the EIP712 hash for EIP-2612 Permit /// @return shares_ amount of minted shares function depositWithSignatureEIP2612( uint256 assets_, address receiver_, uint256 minAmountOut_, uint256 deadline_, bytes calldata signature_ ) external returns (uint256 shares_) { // create allowance through signature_ and spend it (uint8 v_, bytes32 r_, bytes32 s_) = _splitSignature(signature_); // EIP-2612 permit for underlying asset from owner (msg.sender) to spender (this contract) IERC20Permit(address(ASSET)).permit(msg.sender, address(this), assets_, deadline_, v_, r_, s_); // deposit() includes nonReentrant modifier which is enough to have from this point forward shares_ = deposit(assets_, receiver_); _revertIfBelowMinAmountOut(shares_, minAmountOut_); } /// @notice mint amount of `shares_` with EIP-2612 Permit signature for underlying asset approval. /// IMPORTANT: This will revert if the underlying `asset()` does not support EIP-2612. /// Signature should approve a little bit more than expected assets amount (`previewMint()`) to avoid reverts. /// `shares_` must at least be `minMint()` amount; reverts with `fToken__DepositInsignificant()` if not. /// Note there might be tiny inaccuracies between requested `shares_` and actually received shares amount. /// Recommended to use `deposit()` over mint because it is more gas efficient and less likely to revert. /// @param shares_ amount of shares to mint /// @param receiver_ receiver of minted fToken shares /// @param maxAssets_ maximum accepted amount of assets used as input to mint `shares_` /// @param deadline_ deadline for signature validity /// @param signature_ packed signature of signing the EIP712 hash for EIP-2612 Permit /// @return assets_ deposited assets amount function mintWithSignatureEIP2612( uint256 shares_, address receiver_, uint256 maxAssets_, uint256 deadline_, bytes calldata signature_ ) external returns (uint256 assets_) { assets_ = previewMint(shares_); // create allowance through signature_ and spend it (uint8 v_, bytes32 r_, bytes32 s_) = _splitSignature(signature_); // EIP-2612 permit for underlying asset from owner (msg.sender) to spender (this contract) IERC20Permit(address(ASSET)).permit(msg.sender, address(this), assets_, deadline_, v_, r_, s_); // mint() includes nonReentrant modifier which is enough to have from this point forward assets_ = mint(shares_, receiver_); _revertIfAboveMaxAmount(assets_, maxAssets_); } } /// @notice implements fTokens support for deposit / mint via Permit2 signature. abstract contract fTokenPermit2Deposits is fTokenActions { /// @inheritdoc IFToken function depositWithSignature( uint256 assets_, address receiver_, uint256 minAmountOut_, IAllowanceTransfer.PermitSingle calldata permit_, bytes calldata signature_ ) external nonReentrant returns (uint256 shares_) { // give allowance to address(this) via Permit2 signature -> to spend allowance in LiquidityCallback // to transfer funds directly from msg.sender to liquidity PERMIT2.permit( // owner - Who signed the permit and also holds the tokens // @dev Note if this is modified to not be msg.sender, extra steps would be needed for security! // the caller could use this signature and deposit to the balance of receiver_, which could be set to any address, // because it is not included in the signature. Use permitWitnessTransferFrom in that case. Same for `minAmountOut_`. msg.sender, permit_, // permit message signature_ // packed signature of signing the EIP712 hash of `permit_` ); // @dev transfer of tokens from `msg.sender` to liquidity contract happens via `liquidityCallback` shares_ = _executeDeposit(assets_, receiver_, abi.encode(true, msg.sender)); _revertIfBelowMinAmountOut(shares_, minAmountOut_); } /// @inheritdoc IFToken function mintWithSignature( uint256 shares_, address receiver_, uint256 maxAssets_, IAllowanceTransfer.PermitSingle calldata permit_, bytes calldata signature_ ) external nonReentrant returns (uint256 assets_) { assets_ = previewMint(shares_); _revertIfAboveMaxAmount(assets_, maxAssets_); // give allowance to address(this) via Permit2 PermitSingle. to spend allowance in LiquidityCallback // to transfer funds directly from msg.sender to liquidity PERMIT2.permit( // owner - Who signed the permit and also holds the tokens // @dev Note if this is modified to not be msg.sender, extra steps would be needed for security! // the caller could use this signature and deposit to the balance of receiver_, which could be set to any address, // because it is not included in the signature. Use permitWitnessTransferFrom in that case. Same for `minAmountOut_`. msg.sender, permit_, // permit message signature_ // packed signature of signing the EIP712 hash of `permit_` ); // @dev transfer of tokens from `msg.sender` to liquidity contract happens via `liquidityCallback` _executeDeposit(assets_, receiver_, abi.encode(true, msg.sender)); } } /// @title Fluid fToken (Lending with interest) /// @notice fToken is a token that can be used to supply liquidity to the Fluid Liquidity pool and earn interest for doing so. /// The fToken is backed by the underlying balance and can be redeemed for the underlying token at any time. /// The interest is earned via Fluid Liquidity, e.g. because borrowers pay a borrow rate on it. In addition, fTokens may also /// have active rewards going on that count towards the earned yield for fToken holders. /// @dev The fToken implements the ERC20 and ERC4626 standard, which means it can be transferred, minted and burned. /// The fToken supports EIP-2612 permit approvals via signature. /// The fToken implements withdrawals via EIP-2612 permits and deposits with Permit2 or EIP-2612 (if underlying supports it) signatures. /// fTokens are not upgradeable. /// @dev For view methods / accessing data, use the "LendingResolver" periphery contract. contract fToken is fTokenAdmin, fTokenActions, fTokenEIP2612Withdrawals, fTokenPermit2Deposits, fTokenEIP2612Deposits { /// @param liquidity_ liquidity contract address /// @param lendingFactory_ lending factory contract address /// @param asset_ underlying token address constructor( IFluidLiquidity liquidity_, IFluidLendingFactory lendingFactory_, IERC20 asset_ ) Variables(liquidity_, lendingFactory_, asset_) { // set initial values for _liquidityExchangePrice, _tokenExchangePrice and _lastUpdateTimestamp _liquidityExchangePrice = uint64(_getLiquidityExchangePrice()); _tokenExchangePrice = uint64(EXCHANGE_PRICES_PRECISION); _lastUpdateTimestamp = uint40(block.timestamp); } /// @inheritdoc IERC20Metadata function decimals() public view virtual override(ERC20, IERC20Metadata) returns (uint8) { return DECIMALS; } /// @inheritdoc IFToken function liquidityCallback(address token_, uint256 amount_, bytes calldata data_) external virtual override { if (msg.sender != address(LIQUIDITY) || token_ != address(ASSET) || _status != REENTRANCY_ENTERED) { // caller must be liquidity, token must match, and reentrancy status must be REENTRANCY_ENTERED revert FluidLendingError(ErrorTypes.fToken__Unauthorized); } // callback data can be a) an address only b) an address + transfer via permit2 flag set to true // for a) length will be 32, for b) length is 64 if (data_.length == 32) { address from_ = abi.decode(data_, (address)); // transfer `amount_` from `from_` (original deposit msg.sender) to liquidity contract SafeTransfer.safeTransferFrom(address(ASSET), from_, address(LIQUIDITY), amount_); } else { (bool isPermit2_, address from_) = abi.decode(data_, (bool, address)); if (!isPermit2_) { // unexepcted liquidity callback data revert FluidLendingError(ErrorTypes.fToken__InvalidParams); } // transfer `amount_` from `from_` (original deposit msg.sender) to liquidity contract via PERMIT2 PERMIT2.transferFrom(from_, address(LIQUIDITY), uint160(amount_), address(ASSET)); } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.21; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import { IAllowanceTransfer } from "../interfaces/permit2/iAllowanceTransfer.sol"; import { LiquiditySlotsLink } from "../../../libraries/liquiditySlotsLink.sol"; import { IFToken } from "../interfaces/iFToken.sol"; import { IAllowanceTransfer } from "../interfaces/permit2/iAllowanceTransfer.sol"; import { IFluidLendingRewardsRateModel } from "../interfaces/iLendingRewardsRateModel.sol"; import { IFluidLendingFactory } from "../interfaces/iLendingFactory.sol"; import { IFluidLiquidity } from "../../../liquidity/interfaces/iLiquidity.sol"; import { ErrorTypes } from "../errorTypes.sol"; import { Error } from "../error.sol"; abstract contract Constants { /// @dev permit2 contract, deployed to same address on EVM networks, see https://github.com/Uniswap/permit2 IAllowanceTransfer internal constant PERMIT2 = IAllowanceTransfer(0x000000000022D473030F116dDEE9F6B43aC78BA3); /// @dev precision for exchange prices uint256 internal constant EXCHANGE_PRICES_PRECISION = 1e12; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /// @dev max allowed reward rate is 50% uint256 internal constant MAX_REWARDS_RATE = 50 * 1e12; // 50%; /// @dev address of the Liquidity contract. IFluidLiquidity internal immutable LIQUIDITY; /// @dev address of the Lending factory contract. IFluidLendingFactory internal immutable LENDING_FACTORY; /// @dev address of the underlying asset contract. IERC20 internal immutable ASSET; /// @dev number of decimals for the fToken, same as ASSET uint8 internal immutable DECIMALS; /// @dev slot ids in Liquidity contract for underlying token. /// Helps in low gas fetch from liquidity contract by skipping delegate call with `readFromStorage` bytes32 internal immutable LIQUIDITY_EXCHANGE_PRICES_SLOT; bytes32 internal immutable LIQUIDITY_TOTAL_AMOUNTS_SLOT; bytes32 internal immutable LIQUIDITY_USER_SUPPLY_SLOT; /// @param liquidity_ liquidity contract address /// @param lendingFactory_ lending factory contract address /// @param asset_ underlying token address constructor(IFluidLiquidity liquidity_, IFluidLendingFactory lendingFactory_, IERC20 asset_) { DECIMALS = IERC20Metadata(address(asset_)).decimals(); ASSET = asset_; LIQUIDITY = liquidity_; LENDING_FACTORY = lendingFactory_; LIQUIDITY_EXCHANGE_PRICES_SLOT = LiquiditySlotsLink.calculateMappingStorageSlot( LiquiditySlotsLink.LIQUIDITY_EXCHANGE_PRICES_MAPPING_SLOT, _getLiquiditySlotLinksAsset() ); LIQUIDITY_TOTAL_AMOUNTS_SLOT = LiquiditySlotsLink.calculateMappingStorageSlot( LiquiditySlotsLink.LIQUIDITY_TOTAL_AMOUNTS_MAPPING_SLOT, _getLiquiditySlotLinksAsset() ); LIQUIDITY_USER_SUPPLY_SLOT = LiquiditySlotsLink.calculateDoubleMappingStorageSlot( LiquiditySlotsLink.LIQUIDITY_USER_SUPPLY_DOUBLE_MAPPING_SLOT, address(this), _getLiquiditySlotLinksAsset() ); } /// @dev gets asset address for liquidity slot links, extracted to separate method so it can be overridden if needed function _getLiquiditySlotLinksAsset() internal view virtual returns (address) { return address(ASSET); } } abstract contract Variables is ERC20, ERC20Permit, Error, Constants, IFToken { /// @dev prefix for token name. fToken will append the underlying asset name string private constant TOKEN_NAME_PREFIX = "Fluid "; /// @dev prefix for token symbol. fToken will append the underlying asset symbol string private constant TOKEN_SYMBOL_PREFIX = "f"; // ------------ storage variables from inherited contracts come before vars here -------- // _________ ERC20 _______________ // ----------------------- slot 0 --------------------------- // mapping(address => uint256) private _balances; // ----------------------- slot 1 --------------------------- // mapping(address => mapping(address => uint256)) private _allowances; // ----------------------- slot 2 --------------------------- // uint256 private _totalSupply; // ----------------------- slot 3 --------------------------- // string private _name; // ----------------------- slot 4 --------------------------- // string private _symbol; // _________ ERC20Permit _______________ // ----------------------- slot 5 --------------------------- // mapping(address => Counters.Counter) private _nonces; // ----------------------- slot 6 --------------------------- // bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT; // ----------------------- slot 7 --------------------------- /// @dev address of the LendingRewardsRateModel. IFluidLendingRewardsRateModel internal _rewardsRateModel; // -> 12 bytes empty uint96 private __placeholder_gap; // ----------------------- slot 8 --------------------------- // optimized to put all storage variables where a SSTORE happens on actions in the same storage slot /// @dev exchange price for the underlying assset in the liquidity protocol (without rewards) uint64 internal _liquidityExchangePrice; // in 1e12 -> (max value 18_446_744,073709551615) /// @dev exchange price between fToken and the underlying assset (with rewards) uint64 internal _tokenExchangePrice; // in 1e12 -> (max value 18_446_744,073709551615) /// @dev timestamp when exchange prices were updated the last time uint40 internal _lastUpdateTimestamp; /// @dev status for reentrancy guard uint8 internal _status; /// @dev flag to signal if rewards are active without having to read slot 6 bool internal _rewardsActive; // 72 bits empty (9 bytes) // ----------------------- slot 9 --------------------------- /// @dev rebalancer address allowed to call `rebalance()` and source for funding rewards (ReserveContract). address internal _rebalancer; /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ /// @param liquidity_ liquidity contract address /// @param lendingFactory_ lending factory contract address /// @param asset_ underlying token address constructor( IFluidLiquidity liquidity_, IFluidLendingFactory lendingFactory_, IERC20 asset_ ) validAddress(address(liquidity_)) validAddress(address(lendingFactory_)) validAddress(address(asset_)) Constants(liquidity_, lendingFactory_, asset_) ERC20( string(abi.encodePacked(TOKEN_NAME_PREFIX, IERC20Metadata(address(asset_)).name())), string(abi.encodePacked(TOKEN_SYMBOL_PREFIX, IERC20Metadata(address(asset_)).symbol())) ) ERC20Permit(string(abi.encodePacked(TOKEN_NAME_PREFIX, IERC20Metadata(address(asset_)).name()))) {} /// @dev checks that address is not the zero address, reverts if so. Calling the method in the modifier reduces /// bytecode size as modifiers are inlined into bytecode function _checkValidAddress(address value_) internal pure { if (value_ == address(0)) { revert FluidLendingError(ErrorTypes.fToken__InvalidParams); } } /// @dev validates that an address is not the zero address modifier validAddress(address value_) { _checkValidAddress(value_); _; } }
//SPDX-License-Identifier: MIT pragma solidity 0.8.21; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH9 is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; }
//SPDX-License-Identifier: MIT pragma solidity 0.8.21; import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol"; import { IAllowanceTransfer } from "./permit2/iAllowanceTransfer.sol"; import { IFluidLendingRewardsRateModel } from "./iLendingRewardsRateModel.sol"; import { IFluidLendingFactory } from "./iLendingFactory.sol"; import { IFluidLiquidity } from "../../../liquidity/interfaces/iLiquidity.sol"; interface IFTokenAdmin { /// @notice updates the rewards rate model contract. /// Only callable by LendingFactory auths. /// @param rewardsRateModel_ the new rewards rate model contract address. /// can be set to address(0) to set no rewards (to save gas) function updateRewards(IFluidLendingRewardsRateModel rewardsRateModel_) external; /// @notice Balances out the difference between fToken supply at Liquidity vs totalAssets(). /// Deposits underlying from rebalancer address into Liquidity but doesn't mint any shares /// -> thus making deposit available as rewards. /// Only callable by rebalancer. /// @return assets_ amount deposited to Liquidity function rebalance() external payable returns (uint256 assets_); /// @notice gets the liquidity exchange price of the underlying asset, calculates the updated exchange price (with reward rates) /// and writes those values to storage. /// Callable by anyone. /// @return tokenExchangePrice_ exchange price of fToken share to underlying asset /// @return liquidityExchangePrice_ exchange price at Liquidity for the underlying asset function updateRates() external returns (uint256 tokenExchangePrice_, uint256 liquidityExchangePrice_); /// @notice sends any potentially stuck funds to Liquidity contract. Only callable by LendingFactory auths. function rescueFunds(address token_) external; /// @notice Updates the rebalancer address (ReserveContract). Only callable by LendingFactory auths. function updateRebalancer(address rebalancer_) external; } interface IFToken is IERC4626, IFTokenAdmin { /// @notice returns minimum amount required for deposit (rounded up) function minDeposit() external view returns (uint256); /// @notice returns config, rewards and exchange prices data in a single view method. /// @return liquidity_ address of the Liquidity contract. /// @return lendingFactory_ address of the Lending factory contract. /// @return lendingRewardsRateModel_ address of the rewards rate model contract. changeable by LendingFactory auths. /// @return permit2_ address of the Permit2 contract used for deposits / mint with signature /// @return rebalancer_ address of the rebalancer allowed to execute `rebalance()` /// @return rewardsActive_ true if rewards are currently active /// @return liquidityBalance_ current Liquidity supply balance of `address(this)` for the underyling asset /// @return liquidityExchangePrice_ (updated) exchange price for the underlying assset in the liquidity protocol (without rewards) /// @return tokenExchangePrice_ (updated) exchange price between fToken and the underlying assset (with rewards) function getData() external view returns ( IFluidLiquidity liquidity_, IFluidLendingFactory lendingFactory_, IFluidLendingRewardsRateModel lendingRewardsRateModel_, IAllowanceTransfer permit2_, address rebalancer_, bool rewardsActive_, uint256 liquidityBalance_, uint256 liquidityExchangePrice_, uint256 tokenExchangePrice_ ); /// @notice transfers `amount_` of `token_` to liquidity. Only callable by liquidity contract. /// @dev this callback is used to optimize gas consumption (reducing necessary token transfers). function liquidityCallback(address token_, uint256 amount_, bytes calldata data_) external; /// @notice deposit `assets_` amount with Permit2 signature for underlying asset approval. /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of shares is not reached. /// `assets_` must at least be `minDeposit()` amount; reverts otherwise. /// @param assets_ amount of assets to deposit /// @param receiver_ receiver of minted fToken shares /// @param minAmountOut_ minimum accepted amount of shares minted /// @param permit_ Permit2 permit message /// @param signature_ packed signature of signing the EIP712 hash of `permit_` /// @return shares_ amount of minted shares function depositWithSignature( uint256 assets_, address receiver_, uint256 minAmountOut_, IAllowanceTransfer.PermitSingle calldata permit_, bytes calldata signature_ ) external returns (uint256 shares_); /// @notice mint amount of `shares_` with Permit2 signature for underlying asset approval. /// Signature should approve a little bit more than expected assets amount (`previewMint()`) to avoid reverts. /// `shares_` must at least be `minMint()` amount; reverts otherwise. /// Note there might be tiny inaccuracies between requested `shares_` and actually received shares amount. /// Recommended to use `deposit()` over mint because it is more gas efficient and less likely to revert. /// @param shares_ amount of shares to mint /// @param receiver_ receiver of minted fToken shares /// @param maxAssets_ maximum accepted amount of assets used as input to mint `shares_` /// @param permit_ Permit2 permit message /// @param signature_ packed signature of signing the EIP712 hash of `permit_` /// @return assets_ deposited assets amount function mintWithSignature( uint256 shares_, address receiver_, uint256 maxAssets_, IAllowanceTransfer.PermitSingle calldata permit_, bytes calldata signature_ ) external returns (uint256 assets_); } interface IFTokenNativeUnderlying is IFToken { /// @notice address that is mapped to the chain native token at Liquidity function NATIVE_TOKEN_ADDRESS() external view returns (address); /// @notice deposits `msg.value` amount of native token for `receiver_`. /// `msg.value` must be at least `minDeposit()` amount; reverts otherwise. /// Recommended to use `depositNative()` with a `minAmountOut_` param instead to set acceptable limit. /// @return shares_ actually minted shares function depositNative(address receiver_) external payable returns (uint256 shares_); /// @notice same as {depositNative} but with an additional setting for minimum output amount. /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of shares is not reached function depositNative(address receiver_, uint256 minAmountOut_) external payable returns (uint256 shares_); /// @notice mints `shares_` for `receiver_`, paying with underlying native token. /// `shares_` must at least be `minMint()` amount; reverts otherwise. /// `shares_` set to type(uint256).max not supported. /// Note there might be tiny inaccuracies between requested `shares_` and actually received shares amount. /// Recommended to use `depositNative()` over mint because it is more gas efficient and less likely to revert. /// Recommended to use `mintNative()` with a `minAmountOut_` param instead to set acceptable limit. /// @return assets_ deposited assets amount function mintNative(uint256 shares_, address receiver_) external payable returns (uint256 assets_); /// @notice same as {mintNative} but with an additional setting for minimum output amount. /// reverts with `fToken__MaxAmount()` if `maxAssets_` of assets is surpassed to mint `shares_`. function mintNative( uint256 shares_, address receiver_, uint256 maxAssets_ ) external payable returns (uint256 assets_); /// @notice withdraws `assets_` amount in native underlying to `receiver_`, burning shares of `owner_`. /// If `assets_` equals uint256.max then the whole fToken balance of `owner_` is withdrawn.This does not /// consider withdrawal limit at liquidity so best to check with `maxWithdraw()` before. /// Note there might be tiny inaccuracies between requested `assets_` and actually received assets amount. /// Recommended to use `withdrawNative()` with a `maxSharesBurn_` param instead to set acceptable limit. /// @return shares_ burned shares function withdrawNative(uint256 assets_, address receiver_, address owner_) external returns (uint256 shares_); /// @notice same as {withdrawNative} but with an additional setting for minimum output amount. /// reverts with `fToken__MaxAmount()` if `maxSharesBurn_` of shares burned is surpassed. function withdrawNative( uint256 assets_, address receiver_, address owner_, uint256 maxSharesBurn_ ) external returns (uint256 shares_); /// @notice redeems `shares_` to native underlying to `receiver_`, burning shares of `owner_`. /// If `shares_` equals uint256.max then the whole balance of `owner_` is withdrawn.This does not /// consider withdrawal limit at liquidity so best to check with `maxRedeem()` before. /// Recommended to use `withdrawNative()` over redeem because it is more gas efficient and can set specific amount. /// Recommended to use `redeemNative()` with a `minAmountOut_` param instead to set acceptable limit. /// @return assets_ withdrawn assets amount function redeemNative(uint256 shares_, address receiver_, address owner_) external returns (uint256 assets_); /// @notice same as {redeemNative} but with an additional setting for minimum output amount. /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of assets is not reached. function redeemNative( uint256 shares_, address receiver_, address owner_, uint256 minAmountOut_ ) external returns (uint256 assets_); /// @notice withdraw amount of `assets_` in native token with ERC-2612 permit signature for fToken approval. /// `owner_` signs ERC-2612 permit `signature_` to give allowance of fTokens to `msg.sender`. /// Note there might be tiny inaccuracies between requested `assets_` and actually received assets amount. /// allowance via signature should cover `previewWithdraw(assets_)` plus a little buffer to avoid revert. /// Inherent trust assumption that `msg.sender` will set `receiver_` and `minAmountOut_` as `owner_` intends /// (which is always the case when giving allowance to some spender). /// @param sharesToPermit_ shares amount to use for EIP2612 permit(). Should cover `previewWithdraw(assets_)` + small buffer. /// @param assets_ amount of assets to withdraw /// @param receiver_ receiver of withdrawn assets /// @param owner_ owner to withdraw from (must be signature signer) /// @param maxSharesBurn_ maximum accepted amount of shares burned /// @param deadline_ deadline for signature validity /// @param signature_ packed signature of signing the EIP712 hash for ERC-2612 permit /// @return shares_ burned shares amount function withdrawWithSignatureNative( uint256 sharesToPermit_, uint256 assets_, address receiver_, address owner_, uint256 maxSharesBurn_, uint256 deadline_, bytes calldata signature_ ) external returns (uint256 shares_); /// @notice redeem amount of `shares_` as native token with ERC-2612 permit signature for fToken approval. /// `owner_` signs ERC-2612 permit `signature_` to give allowance of fTokens to `msg.sender`. /// Note there might be tiny inaccuracies between requested `shares_` to redeem and actually burned shares. /// allowance via signature must cover `shares_` plus a tiny buffer. /// Inherent trust assumption that `msg.sender` will set `receiver_` and `minAmountOut_` as `owner_` intends /// (which is always the case when giving allowance to some spender). /// Recommended to use `withdrawNative()` over redeem because it is more gas efficient and can set specific amount. /// @param shares_ amount of shares to redeem /// @param receiver_ receiver of withdrawn assets /// @param owner_ owner to withdraw from (must be signature signer) /// @param minAmountOut_ minimum accepted amount of assets withdrawn /// @param deadline_ deadline for signature validity /// @param signature_ packed signature of signing the EIP712 hash for ERC-2612 permit /// @return assets_ withdrawn assets amount function redeemWithSignatureNative( uint256 shares_, address receiver_, address owner_, uint256 minAmountOut_, uint256 deadline_, bytes calldata signature_ ) external returns (uint256 assets_); }
//SPDX-License-Identifier: MIT pragma solidity 0.8.21; import { IFluidLiquidity } from "../../../liquidity/interfaces/iLiquidity.sol"; interface IFluidLendingFactoryAdmin { /// @notice reads if a certain `auth_` address is an allowed auth or not. Owner is auth by default. function isAuth(address auth_) external view returns (bool); /// @notice Sets an address as allowed auth or not. Only callable by owner. /// @param auth_ address to set auth value for /// @param allowed_ bool flag for whether address is allowed as auth or not function setAuth(address auth_, bool allowed_) external; /// @notice reads if a certain `deployer_` address is an allowed deployer or not. Owner is deployer by default. function isDeployer(address deployer_) external view returns (bool); /// @notice Sets an address as allowed deployer or not. Only callable by owner. /// @param deployer_ address to set deployer value for /// @param allowed_ bool flag for whether address is allowed as deployer or not function setDeployer(address deployer_, bool allowed_) external; /// @notice Sets the `creationCode_` bytecode for a certain `fTokenType_`. Only callable by auths. /// @param fTokenType_ the fToken Type used to refer the creation code /// @param creationCode_ contract creation code. can be set to bytes(0) to remove a previously available `fTokenType_` function setFTokenCreationCode(string memory fTokenType_, bytes calldata creationCode_) external; /// @notice creates token for `asset_` for a lending protocol with interest. Only callable by deployers. /// @param asset_ address of the asset /// @param fTokenType_ type of fToken: /// - if it's the native token, it should use `NativeUnderlying` /// - otherwise it should use `fToken` /// - could be more types available, check `fTokenTypes()` /// @param isNativeUnderlying_ flag to signal fToken type that uses native underlying at Liquidity /// @return token_ address of the created token function createToken( address asset_, string calldata fTokenType_, bool isNativeUnderlying_ ) external returns (address token_); } interface IFluidLendingFactory is IFluidLendingFactoryAdmin { /// @notice list of all created tokens function allTokens() external view returns (address[] memory); /// @notice list of all fToken types that can be deployed function fTokenTypes() external view returns (string[] memory); /// @notice returns the creation code for a certain `fTokenType_` function fTokenCreationCode(string memory fTokenType_) external view returns (bytes memory); /// @notice address of the Liquidity contract. function LIQUIDITY() external view returns (IFluidLiquidity); /// @notice computes deterministic token address for `asset_` for a lending protocol /// @param asset_ address of the asset /// @param fTokenType_ type of fToken: /// - if it's the native token, it should use `NativeUnderlying` /// - otherwise it should use `fToken` /// - could be more types available, check `fTokenTypes()` /// @return token_ detemrinistic address of the computed token function computeToken(address asset_, string calldata fTokenType_) external view returns (address token_); }
//SPDX-License-Identifier: MIT pragma solidity 0.8.21; interface IFluidLendingRewardsRateModel { /// @notice Calculates the current rewards rate (APR) /// @param totalAssets_ amount of assets in the lending /// @return rate_ rewards rate percentage per year with 1e12 RATE_PRECISION, e.g. 1e12 = 1%, 1e14 = 100% /// @return ended_ flag to signal that rewards have ended (always 0 going forward) /// @return startTime_ start time of rewards to compare against last update timestamp function getRate(uint256 totalAssets_) external view returns (uint256 rate_, bool ended_, uint256 startTime_); /// @notice Returns config constants for rewards rate model function getConfig() external view returns ( uint256 duration_, uint256 startTime_, uint256 endTime_, uint256 startTvl_, uint256 maxRate_, uint256 rewardAmount_, address initiator_ ); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.21; /// @title AllowanceTransfer /// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts /// @dev Requires user's token approval on the Permit2 contract /// from https://github.com/Uniswap/permit2/blob/main/src/interfaces/ISignatureTransfer.sol. /// Copyright (c) 2022 Uniswap Labs interface IAllowanceTransfer { function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Thrown when an allowance on a token has expired. /// @param deadline The timestamp at which the allowed amount is no longer valid error AllowanceExpired(uint256 deadline); /// @notice Thrown when an allowance on a token has been depleted. /// @param amount The maximum amount allowed error InsufficientAllowance(uint256 amount); /// @notice Thrown when too many nonces are invalidated. error ExcessiveInvalidation(); /// @notice Emits an event when the owner successfully invalidates an ordered nonce. event NonceInvalidation( address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce ); /// @notice Emits an event when the owner successfully sets permissions on a token for the spender. event Approval( address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration ); /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender. event Permit( address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration, uint48 nonce ); /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function. event Lockdown(address indexed owner, address token, address spender); /// @notice The permit data for a token struct PermitDetails { // ERC20 token address address token; // the maximum amount allowed to spend uint160 amount; // timestamp at which a spender's token allowances become invalid uint48 expiration; // an incrementing value indexed per owner,token,and spender for each signature uint48 nonce; } /// @notice The permit message signed for a single token allownce struct PermitSingle { // the permit data for a single token alownce PermitDetails details; // address permissioned on the allowed tokens address spender; // deadline on the permit signature uint256 sigDeadline; } /// @notice The permit message signed for multiple token allowances struct PermitBatch { // the permit data for multiple token allowances PermitDetails[] details; // address permissioned on the allowed tokens address spender; // deadline on the permit signature uint256 sigDeadline; } /// @notice The saved permissions /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message /// @dev Setting amount to type(uint160).max sets an unlimited approval struct PackedAllowance { // amount allowed uint160 amount; // permission expiry uint48 expiration; // an incrementing value indexed per owner,token,and spender for each signature uint48 nonce; } /// @notice A token spender pair. struct TokenSpenderPair { // the token the spender is approved address token; // the spender address address spender; } /// @notice Details for a token transfer. struct AllowanceTransferDetails { // the owner of the token address from; // the recipient of the token address to; // the amount of the token uint160 amount; // the token to be transferred address token; } /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval. /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress] /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals. function allowance( address user, address token, address spender ) external view returns (uint160 amount, uint48 expiration, uint48 nonce); /// @notice Approves the spender to use up to amount of the specified token up until the expiration /// @param token The token to approve /// @param spender The spender address to approve /// @param amount The approved amount of the token /// @param expiration The timestamp at which the approval is no longer valid /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve /// @dev Setting amount to type(uint160).max sets an unlimited approval function approve(address token, address spender, uint160 amount, uint48 expiration) external; /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce /// @param owner The owner of the tokens being approved /// @param permitSingle Data signed over by the owner specifying the terms of approval /// @param signature The owner's signature over the permit data function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external; /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce /// @param owner The owner of the tokens being approved /// @param permitBatch Data signed over by the owner specifying the terms of approval /// @param signature The owner's signature over the permit data function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external; /// @notice Transfer approved tokens from one address to another /// @param from The address to transfer from /// @param to The address of the recipient /// @param amount The amount of the token to transfer /// @param token The token address to transfer /// @dev Requires the from address to have approved at least the desired amount /// of tokens to msg.sender. function transferFrom(address from, address to, uint160 amount, address token) external; /// @notice Transfer approved tokens in a batch /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers /// @dev Requires the from addresses to have approved at least the desired amount /// of tokens to msg.sender. function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external; /// @notice Enables performing a "lockdown" of the sender's Permit2 identity /// by batch revoking approvals /// @param approvals Array of approvals to revoke. function lockdown(TokenSpenderPair[] calldata approvals) external; /// @notice Invalidate nonces for a given (token, spender) pair /// @param token The token to invalidate nonces for /// @param spender The spender to invalidate nonces for /// @param newNonce The new nonce to set. Invalidates all nonces less than it. /// @dev Can't invalidate more than 2**16 nonces per transaction. function invalidateNonces(address token, address spender, uint48 newNonce) external; }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol) library FixedPointMathLib { /*////////////////////////////////////////////////////////////// SIMPLIFIED FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ uint256 internal constant MAX_UINT256 = 2**256 - 1; uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up. } function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down. } function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up. } /*////////////////////////////////////////////////////////////// LOW LEVEL FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) { revert(0, 0) } // Divide x * y by the denominator. z := div(mul(x, y), denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) { revert(0, 0) } // If x * y modulo the denominator is strictly greater than 0, // 1 is added to round up the division of x * y by the denominator. z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator)) } } function rpow( uint256 x, uint256 n, uint256 scalar ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := scalar } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store scalar in z for now. z := scalar } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, scalar) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, scalar) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, scalar) } } } } } /*////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { let y := x // We start y at x, which will help us make our initial estimate. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // We check y >= 2^(k + 8) but shift right by k bits // each branch to ensure that if x >= 256, then y >= 256. if iszero(lt(y, 0x10000000000000000000000000000000000)) { y := shr(128, y) z := shl(64, z) } if iszero(lt(y, 0x1000000000000000000)) { y := shr(64, y) z := shl(32, z) } if iszero(lt(y, 0x10000000000)) { y := shr(32, y) z := shl(16, z) } if iszero(lt(y, 0x1000000)) { y := shr(16, y) z := shl(8, z) } // Goal was to get z*z*y within a small factor of x. More iterations could // get y in a tighter range. Currently, we will have y in [256, 256*2^16). // We ensured y >= 256 so that the relative difference between y and y+1 is small. // That's not possible if x < 256 but we can just verify those cases exhaustively. // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256. // Correctness can be checked exhaustively for x < 256, so we assume y >= 256. // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps. // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256. // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18. // There is no overflow risk here since y < 2^136 after the first branch above. z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If x+1 is a perfect square, the Babylonian method cycles between // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case. // If you don't care whether the floor or ceil square root is returned, you can remove this statement. z := sub(z, lt(div(x, z), z)) } } function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Mod x by y. Note this will return // 0 instead of reverting if y is zero. z := mod(x, y) } } function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { // Divide x by y. Note this will return // 0 instead of reverting if y is zero. r := div(x, y) } } function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Add 1 to x * y if x % y > 0. Note this will // return 0 instead of reverting if y is zero. z := add(gt(mod(x, y), 0), div(x, y)) } } }
{ "optimizer": { "enabled": true, "runs": 10000000 }, "evmVersion": "paris", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"contract IFluidLiquidity","name":"liquidity_","type":"address"},{"internalType":"contract IFluidLendingFactory","name":"lendingFactory_","type":"address"},{"internalType":"contract IWETH9","name":"weth_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"errorId_","type":"uint256"}],"name":"FluidLendingError","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorId_","type":"uint256"}],"name":"FluidLiquidityCalcsError","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorId_","type":"uint256"}],"name":"FluidSafeTransferError","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":"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":[{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"LogRebalance","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"LogRescueFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenExchangePrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"liquidityExchangePrice","type":"uint256"}],"name":"LogUpdateRates","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"rebalancer","type":"address"}],"name":"LogUpdateRebalancer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IFluidLendingRewardsRateModel","name":"rewardsRateModel","type":"address"}],"name":"LogUpdateRewards","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"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"NATIVE_TOKEN_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"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":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"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":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"}],"name":"depositNative","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"receiver_","type":"address"}],"name":"depositNative","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"},{"components":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint160","name":"amount","type":"uint160"},{"internalType":"uint48","name":"expiration","type":"uint48"},{"internalType":"uint48","name":"nonce","type":"uint48"}],"internalType":"struct IAllowanceTransfer.PermitDetails","name":"details","type":"tuple"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"sigDeadline","type":"uint256"}],"internalType":"struct IAllowanceTransfer.PermitSingle","name":"permit_","type":"tuple"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"depositWithSignature","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"depositWithSignatureEIP2612","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getData","outputs":[{"internalType":"contract IFluidLiquidity","name":"liquidity_","type":"address"},{"internalType":"contract IFluidLendingFactory","name":"lendingFactory_","type":"address"},{"internalType":"contract IFluidLendingRewardsRateModel","name":"lendingRewardsRateModel_","type":"address"},{"internalType":"contract IAllowanceTransfer","name":"permit2_","type":"address"},{"internalType":"address","name":"rebalancer_","type":"address"},{"internalType":"bool","name":"rewardsActive_","type":"bool"},{"internalType":"uint256","name":"liquidityBalance_","type":"uint256"},{"internalType":"uint256","name":"liquidityExchangePrice_","type":"uint256"},{"internalType":"uint256","name":"tokenExchangePrice_","type":"uint256"}],"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":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"liquidityCallback","outputs":[],"stateMutability":"nonpayable","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":[],"name":"minDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"maxAssets_","type":"uint256"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"}],"name":"mintNative","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"maxAssets_","type":"uint256"}],"name":"mintNative","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"maxAssets_","type":"uint256"},{"components":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint160","name":"amount","type":"uint160"},{"internalType":"uint48","name":"expiration","type":"uint48"},{"internalType":"uint48","name":"nonce","type":"uint48"}],"internalType":"struct IAllowanceTransfer.PermitDetails","name":"details","type":"tuple"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"sigDeadline","type":"uint256"}],"internalType":"struct IAllowanceTransfer.PermitSingle","name":"permit_","type":"tuple"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"mintWithSignature","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"maxAssets_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"mintWithSignatureEIP2612","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"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":[{"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":"rebalance","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","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":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"}],"name":"redeemNative","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"}],"name":"redeemNative","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"redeemWithSignature","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"redeemWithSignatureNative","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token_","type":"address"}],"name":"rescueFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"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":[],"name":"updateRates","outputs":[{"internalType":"uint256","name":"tokenExchangePrice_","type":"uint256"},{"internalType":"uint256","name":"liquidityExchangePrice_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newRebalancer_","type":"address"}],"name":"updateRebalancer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IFluidLendingRewardsRateModel","name":"rewardsRateModel_","type":"address"}],"name":"updateRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"maxSharesBurn_","type":"uint256"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"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":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"}],"name":"withdrawNative","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"maxSharesBurn_","type":"uint256"}],"name":"withdrawNative","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"sharesToPermit_","type":"uint256"},{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"maxSharesBurn_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"withdrawWithSignature","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"sharesToPermit_","type":"uint256"},{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"maxSharesBurn_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"withdrawWithSignatureNative","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]
Contract Creation Code
6102206040523480156200001257600080fd5b5060405162005e9f38038062005e9f8339810160408190526200003591620007d2565b82828282828282828260405180604001604052806006815260200165023363ab4b2160d51b815250846001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa1580156200009c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052620000c6919081019062000862565b604051602001620000d99291906200091a565b60405160208183030381529060405280604051806040016040528060018152602001603160f81b81525060405180604001604052806006815260200165023363ab4b2160d51b815250876001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa15801562000161573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200018b919081019062000862565b6040516020016200019e9291906200091a565b604051602081830303815290604052604051806040016040528060018152602001603360f91b815250886001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa15801562000206573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262000230919081019062000862565b604051602001620002439291906200091a565b60408051601f198184030181529190526003620002618382620009d6565b506004620002708282620009d6565b5050825160208085019190912083518483012060e08290526101008190524660a0818152604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81880181905281830187905260608201869052608082019490945230818401528151808203909301835260c0019052805194019390932091935091906080523060c0526101205250506040805163313ce56760e01b815290516001600160a01b038616945063313ce5679350600480830193506020928290030181865afa15801562000349573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200036f919062000aa2565b60ff166101a0526001600160a01b0390811661018090815292811661014090815291166101609081526040805173eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee60208281018290526005838501528351808403850181526060840185528051908201206101c05260808301829052600760a0808501919091528451808503909101815260c0840185528051908201206101e0523060e08401526008610100808501919091528451808503909101815261012084018552805190820120958301919091528184019490945281518082039093018352909301909252815191012061020052826200046081620004f5565b826200046c81620004f5565b826200047881620004f5565b50506008805460ff60a81b1916600160a81b179055506200049d925050620005299050565b600880546001600160401b03929092166001600160801b0319909216919091176ce8d4a5100000000000000000001764ffffffffff60801b1916600160801b4264ffffffffff16021790555062000afe945050505050565b6001600160a01b038116620005265760405163694bda1d60e01b8152614e2460048201526024015b60405180910390fd5b50565b6000620005ae610140516001600160a01b031663b5c736e46101c0516040518263ffffffff1660e01b81526004016200056491815260200190565b602060405180830381865afa15801562000582573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620005a8919062000ace565b620005b4565b50919050565b6001600160401b03605b82901c811690609b83901c16811580620005d6575080155b15620005fb57604051636a86ba8960e11b81526201117160048201526024016200051d565b61ffff8316603a84901c6401ffffffff16428181039160ea87901c617fff1691148062000626575082155b80620006325750806001145b156200064057505050915091565b64496cebb80084840283020484019350617fff60db87901c169250826001036200066c57505050915091565b82600116600103620006c65760019290921c91826c7e37be2022c0914b2680000000816200069e576200069e62000ae8565b049250612710601e87901c613fff166b033b2e3c9fd0803ce8000000850102049250620006f3565b60019290921c916305f5e100601e87901c613fff166127108501026b033b2e3c9fd0803ce8000000020492505b806001166001036200072f5760011c61271081016b033b2e3c9fd0803ce800000082028162000726576200072662000ae8565b04905062000768565b60011c61271081016b033b2e3c9fd0803ce800000082028162000756576200075662000ae8565b046b033b2e3c9fd0803ce80000000390505b760a70c3c40a64e6c51999090b65f67d92400000000000008382026127100261ffff881691900402601087901c613fff16612710030292506801b5a660ea44b8000085840283020485019450505050915091565b6001600160a01b03811681146200052657600080fd5b600080600060608486031215620007e857600080fd5b8351620007f581620007bc565b60208501519093506200080881620007bc565b60408501519092506200081b81620007bc565b809150509250925092565b634e487b7160e01b600052604160045260246000fd5b60005b83811015620008595781810151838201526020016200083f565b50506000910152565b6000602082840312156200087557600080fd5b81516001600160401b03808211156200088d57600080fd5b818401915084601f830112620008a257600080fd5b815181811115620008b757620008b762000826565b604051601f8201601f19908116603f01168101908382118183101715620008e257620008e262000826565b81604052828152876020848701011115620008fc57600080fd5b6200090f8360208301602088016200083c565b979650505050505050565b600083516200092e8184602088016200083c565b835190830190620009448183602088016200083c565b01949350505050565b600181811c908216806200096257607f821691505b602082108103620005ae57634e487b7160e01b600052602260045260246000fd5b601f821115620009d157600081815260208120601f850160051c81016020861015620009ac5750805b601f850160051c820191505b81811015620009cd57828155600101620009b8565b5050505b505050565b81516001600160401b03811115620009f257620009f262000826565b62000a0a8162000a0384546200094d565b8462000983565b602080601f83116001811462000a42576000841562000a295750858301515b600019600386901b1c1916600185901b178555620009cd565b600085815260208120601f198616915b8281101562000a735788860151825594840194600190910190840162000a52565b508582101562000a925787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60006020828403121562000ab557600080fd5b815160ff8116811462000ac757600080fd5b9392505050565b60006020828403121562000ae157600080fd5b5051919050565b634e487b7160e01b600052601260045260246000fd5b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c0516101e0516102005161526a62000c35600039600081816131690152613a640152600081816112b701526113fb015260006127860152600061050401526000818161056501528181611210015281816117f201528181611c750152818161234101528181613479015281816134fd0152818161366a015281816136e5015261373b0152600081816110950152613551015260008181611073015281816113010152818161143e01528181612491015281816124ef015281816127c80152818161312d0152818161391e01528181613aa401528181613b84015261482d0152600061307d015260006130cc015260006130a7015260006130000152600061302a01526000613054015261526a6000f3fe60806040526004361061038f5760003560e01c80637d7c2a1c116101dc578063ba08765211610102578063dd62ed3e116100a0578063e53b20171161006f578063e53b201714610b38578063eb26620c14610b58578063ef8b30f714610b78578063f5a35aaa14610b9857600080fd5b8063dd62ed3e14610a7d578063df2ebdbb14610ad0578063e083be2214610af8578063e359754814610b1857600080fd5b8063c6e6f592116100dc578063c6e6f592146109fd578063ce96cb7714610a1d578063d505accf14610a3d578063d905777e14610a5d57600080fd5b8063ba0876521461099d578063bc157ac1146109bd578063c63d75b6146109dd57600080fd5b80639f40a7b31161017a578063ad20750111610149578063ad2075011461091d578063b046a4491461093d578063b3d7f6b91461095d578063b460af941461097d57600080fd5b80639f40a7b31461089d578063a318c1a4146108bd578063a457c2d7146108dd578063a9059cbb146108fd57600080fd5b8063836a1040116101b6578063836a1040146108285780638c87483a1461084857806394bf804d1461086857806395d89b411461088857600080fd5b80637d7c2a1c146107ed5780637ecebe00146107f5578063805411871461081557600080fd5b806338d52e0f116102c157806341b3d1851161025f578063635c31c21161022e578063635c31c21461074a5780636e553f651461076a57806370a082311461078a578063740c955e146107cd57600080fd5b806341b3d185146106d35780634cdad506146106e857806350cc0f8f146107085780635fd619651461072857600080fd5b80633bc5de301161029b5780633bc5de30146105ea5780633c3821f4146106695780633f4c093014610693578063402d267d146106b357600080fd5b806338d52e0f1461055657806339509351146105aa5780633badef91146105ca57600080fd5b806318160ddd1161032e5780632ae06214116103085780632ae06214146104d0578063313ce567146104f057806333bb7f911461052e5780633644e5151461054157600080fd5b806318160ddd1461047b5780632126e91e1461049057806323b872dd146104b057600080fd5b806306fdde031161036a57806306fdde03146103e957806307a2d13a1461040b578063095ea7b31461042b5780630a28a4771461045b57600080fd5b8062acb7361461039b57806301e1d114146103c157806302279b4a146103d657600080fd5b3661039657005b600080fd5b6103ae6103a9366004614941565b610bb8565b6040519081526020015b60405180910390f35b3480156103cd57600080fd5b506103ae610c60565b6103ae6103e4366004614971565b610c9f565b3480156103f557600080fd5b506103fe610cbc565b6040516103b89190614a01565b34801561041757600080fd5b506103ae610426366004614a14565b610d4e565b34801561043757600080fd5b5061044b610446366004614971565b610d76565b60405190151581526020016103b8565b34801561046757600080fd5b506103ae610476366004614a14565b610d8e565b34801561048757600080fd5b506002546103ae565b34801561049c57600080fd5b506103ae6104ab366004614a2d565b610daf565b3480156104bc57600080fd5b5061044b6104cb366004614a6f565b610e78565b3480156104dc57600080fd5b506103ae6104eb366004614ab0565b610e9c565b3480156104fc57600080fd5b5060405160ff7f00000000000000000000000000000000000000000000000000000000000000001681526020016103b8565b6103ae61053c366004614af8565b610ebd565b34801561054d57600080fd5b506103ae610f16565b34801561056257600080fd5b507f00000000000000000000000000000000000000000000000000000000000000005b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016103b8565b3480156105b657600080fd5b5061044b6105c5366004614971565b610f25565b3480156105d657600080fd5b506103ae6105e5366004614a2d565b610f71565b3480156105f657600080fd5b506105ff61103f565b6040805173ffffffffffffffffffffffffffffffffffffffff9a8b168152988a1660208a0152968916968801969096529387166060870152959091166080850152151560a084015260c083019390935260e0820192909252610100810191909152610120016103b8565b34801561067557600080fd5b5061067e61112b565b604080519283526020830191909152016103b8565b34801561069f57600080fd5b506103ae6106ae366004614b5e565b611149565b3480156106bf57600080fd5b506103ae6106ce366004614af8565b61128f565b3480156106df57600080fd5b506103ae6113d3565b3480156106f457600080fd5b506103ae610703366004614a14565b6114d4565b34801561071457600080fd5b506103ae610723366004614bd1565b6114df565b34801561073457600080fd5b50610748610743366004614af8565b6115b7565b005b34801561075657600080fd5b506103ae610765366004614c60565b61167d565b34801561077657600080fd5b506103ae610785366004614941565b611793565b34801561079657600080fd5b506103ae6107a5366004614af8565b73ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b3480156107d957600080fd5b506103ae6107e8366004614ce8565b61188d565b6103ae611972565b34801561080157600080fd5b506103ae610810366004614af8565b611ab7565b6103ae610823366004614d6e565b611ae2565b34801561083457600080fd5b506103ae610843366004614d6e565b611afa565b34801561085457600080fd5b506103ae610863366004614c60565b611b06565b34801561087457600080fd5b506103ae610883366004614941565b611c16565b34801561089457600080fd5b506103fe611d20565b3480156108a957600080fd5b506103ae6108b8366004614ab0565b611d2f565b3480156108c957600080fd5b506103ae6108d8366004614ab0565b611d3c565b3480156108e957600080fd5b5061044b6108f8366004614971565b611d55565b34801561090957600080fd5b5061044b610918366004614971565b611e26565b34801561092957600080fd5b50610748610938366004614d95565b611e34565b34801561094957600080fd5b50610748610958366004614af8565b611e6a565b34801561096957600080fd5b506103ae610978366004614a14565b611eec565b34801561098957600080fd5b506103ae610998366004614a2d565b611f0d565b3480156109a957600080fd5b506103ae6109b8366004614a2d565b611f7b565b3480156109c957600080fd5b506103ae6109d8366004614d6e565b611fed565b3480156109e957600080fd5b506103ae6109f8366004614af8565b612005565b348015610a0957600080fd5b506103ae610a18366004614a14565b612014565b348015610a2957600080fd5b506103ae610a38366004614af8565b612035565b348015610a4957600080fd5b50610748610a58366004614df1565b612089565b348015610a6957600080fd5b506103ae610a78366004614af8565b612248565b348015610a8957600080fd5b506103ae610a98366004614e68565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260016020908152604080832093909416825291909152205490565b348015610adc57600080fd5b5061058573eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b348015610b0457600080fd5b506103ae610b13366004614b5e565b612286565b348015610b2457600080fd5b506103ae610b33366004614ce8565b6123b3565b348015610b4457600080fd5b50610748610b53366004614af8565b61243f565b348015610b6457600080fd5b506103ae610b73366004614ab0565b6125fa565b348015610b8457600080fd5b506103ae610b93366004614a14565b612607565b348015610ba457600080fd5b506103ae610bb3366004614bd1565b612612565b6000610bc2612687565b610bcb83611eec565b905080341015610c10576040517f694bda1d00000000000000000000000000000000000000000000000000000000815261520960048201526024015b60405180910390fd5b610c1982612725565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905592915050565b600080610c73610c6e61275e565b61283e565b50905064e8d4a51000610c8560025490565b610c8f9083614ec5565b610c999190614f0b565b91505090565b6000610caa83610ebd565b9050610cb68183612a1e565b92915050565b606060038054610ccb90614f46565b80601f0160208091040260200160405190810160405280929190818152602001828054610cf790614f46565b8015610d445780601f10610d1957610100808354040283529160200191610d44565b820191906000526020600020905b815481529060010190602001808311610d2757829003601f168201915b5050505050905090565b600080610d5c610c6e61275e565b509050610d6f838264e8d4a51000612a60565b9392505050565b600033610d84818585612a9c565b5060019392505050565b600080610d9c610c6e61275e565b509050610d6f8364e8d4a5100083612c4f565b6000610db9612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403610dfc5733600090815260208190526040902054610df9906114d4565b93505b610e07848484612c93565b90503373ffffffffffffffffffffffffffffffffffffffff831614610e3157610e31823383612ca0565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559392505050565b600033610e86858285612ca0565b610e91858585612d77565b506001949350505050565b6000610ea9858585610f71565b9050610eb58183612a1e565b949350505050565b6000610ec7612687565b610ed082612725565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905592915050565b6000610f20612fe6565b905090565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff87168452909152812054909190610d849082908690610f6c908790614f93565b612a9c565b6000610f7b612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403610fb5573360009081526020819052604090205493505b610fbe846114d4565b90506000610fcd828585612c93565b90503373ffffffffffffffffffffffffffffffffffffffff841614610ff757610ff7833383612ca0565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559392505050565b600080600080600080600080600061105561275e565b915060006110628361283e565b6007546009546008549395509193507f0000000000000000000000000000000000000000000000000000000000000000927f00000000000000000000000000000000000000000000000000000000000000009273ffffffffffffffffffffffffffffffffffffffff928316926e22d473030f116ddee9f6b43ac78ba392911690760100000000000000000000000000000000000000000000900460ff168015611109575085155b61111161311a565b995099509950995099509950995050909192939495969798565b60008061113661275e565b905061114381600161321e565b91509091565b600061115487611eec565b9050600080600061119a86868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061339892505050565b6040517fd505accf00000000000000000000000000000000000000000000000000000000815233600482015230602482015260448101889052606481018b905260ff8416608482015260a4810183905260c48101829052929550909350915073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063d505accf9060e401600060405180830381600087803b15801561125457600080fd5b505af1158015611268573d6000803e3d6000fd5b505050506112768a8a611c16565b935061128284896133c7565b5050509695505050505050565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f00000000000000000000000000000000000000000000000000000000000000006004820152600090819067ffffffffffffffff9073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063b5c736e490602401602060405180830381865afa158015611348573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061136c9190614fa6565b16600881901c60ff9091161b905064e8d4a5100061138861275e565b82028161139757611397614edc565b0490506f7fffffffffffff7fffffffffffffffff8111156113bb5750600092915050565b6f7fffffffffffffffffffffffffffffff0392915050565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f00000000000000000000000000000000000000000000000000000000000000006004820152600090819060ff9073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063b5c736e490602401602060405180830381865afa158015611485573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114a99190614fa6565b166001901b905060006114bc6001611eec565b90508082116114cb57806114cd565b815b9250505090565b6000610cb682610d4e565b60006114e9612687565b73ffffffffffffffffffffffffffffffffffffffff8616330361153c576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e266004820152602401610c07565b611549868a868686613405565b611554888888613468565b905061156081866133c7565b61156b863383612ca0565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905598975050505050505050565b6115bf613523565b6115c761112b565b5050600780547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff8316908117909155600880547fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff16821515760100000000000000000000000000000000000000000000021790556040517fd14b198a72267efb36b8bbc193eb6d52a00d1f61799029250f6a520ad47be82d90600090a250565b6000611687612687565b6040517f2b67b5700000000000000000000000000000000000000000000000000000000081526e22d473030f116ddee9f6b43ac78ba390632b67b570906116d8903390889088908890600401615023565b600060405180830381600087803b1580156116f257600080fd5b505af1158015611706573d6000803e3d6000fd5b50506040805160016020820152339181019190915261173d925089915088906060015b60405160208183030381529060405261360d565b90506117498186612a1e565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559695505050505050565b600061179d612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8303611875576040517f70a082310000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16906370a0823190602401602060405180830381865afa15801561184e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118729190614fa6565b92505b60408051336020820152610e31918591859101611729565b6000611897612687565b73ffffffffffffffffffffffffffffffffffffffff861633036118ea576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e266004820152602401610c07565b6118f3886114d4565b90506118ff8186612a1e565b61190c8689868686613405565b6000611919828989613468565b9050611926873383612ca0565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167501000000000000000000000000000000000000000000179055979650505050505050565b600061197c612687565b60095473ffffffffffffffffffffffffffffffffffffffff1633146119d1576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e296004820152602401610c07565b6119d961311a565b6119e1610c60565b6119eb91906150dd565b9050803410156119fc575034611a17565b80341115611a1757611a1733611a1283346150dd565b6137bb565b60408051600080825260208201909252611a3290839061391a565b9050611a3f81600161321e565b506040518281527fe97ad8b810ae9d9e29aa69dc04d4ac2e3e71d65307830ccb97c8f876dfc439319060200160405180910390a150600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905590565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260056020526040812054610cb6565b6000611aee8484610bb8565b9050610d6f81836133c7565b6000611aee8484611c16565b6000611b10612687565b611b1987611eec565b9050611b2581866133c7565b6040517f2b67b5700000000000000000000000000000000000000000000000000000000081526e22d473030f116ddee9f6b43ac78ba390632b67b57090611b76903390889088908890600401615023565b600060405180830381600087803b158015611b9057600080fd5b505af1158015611ba4573d6000803e3d6000fd5b505060408051600160208201523391810191909152611bcb92508391508890606001611729565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559695505050505050565b6000611c20612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8303611cfc576040517f70a082310000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16906370a0823190602401602060405180830381865afa158015611cd1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cf59190614fa6565b9050611d08565b611d0583611eec565b90505b60408051336020820152610c19918391859101611729565b606060048054610ccb90614f46565b6000610ea9858585611f7b565b6000611d49858585611f0d565b9050610eb581836133c7565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8716845290915281205490919083811015611e19576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7760448201527f207a65726f0000000000000000000000000000000000000000000000000000006064820152608401610c07565b610e918286868403612a9c565b600033610d84818585612d77565b6040517f694bda1d00000000000000000000000000000000000000000000000000000000815261520a6004820152602401610c07565b80611e74816139e8565b611e7c613523565b600980547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff84169081179091556040517fdb94ee7fd8b5bbf8f6d59e76731ff4b4f5a02ab3af1d3e0c774862cf96ff613b90600090a25050565b600080611efa610c6e61275e565b509050610d6f838264e8d4a51000612c4f565b6000611f17612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403611f7057611f6d6107038373ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b93505b610e07848484613468565b6000611f85612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403611fd55773ffffffffffffffffffffffffffffffffffffffff821660009081526020819052604090205493505b611fde846114d4565b90506000610fcd828585613468565b6000611ff98484611793565b9050610d6f8183612a1e565b6000610cb6610a18600061128f565b600080612022610c6e61275e565b509050610d6f8364e8d4a5100083612a60565b600080612040613a3c565b905060006120736104268573ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b90508082106120825780610eb5565b5092915050565b834211156120f3576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606401610c07565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886121228c613bbc565b60408051602081019690965273ffffffffffffffffffffffffffffffffffffffff94851690860152929091166060840152608083015260a082015260c0810186905260e001604051602081830303815290604052805190602001209050600061218a82613bef565b9050600061219a82878787613c58565b90508973ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614612231576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152606401610c07565b61223c8a8a8a612a9c565b50505050505050505050565b600080612256610a18613a3c565b905060006120738473ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b6000806000806122cb86868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061339892505050565b6040517fd505accf000000000000000000000000000000000000000000000000000000008152336004820152306024820152604481018e9052606481018b905260ff8416608482015260a4810183905260c48101829052929550909350915073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063d505accf9060e401600060405180830381600087803b15801561238557600080fd5b505af1158015612399573d6000803e3d6000fd5b505050506123a78a8a611793565b93506112828489612a1e565b60006123bd612687565b73ffffffffffffffffffffffffffffffffffffffff86163303612410576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e266004820152602401610c07565b612419886114d4565b90506124258186612a1e565b6124328689868686613405565b6000611919828989612c93565b612447612687565b61244f613523565b7fffffffffffffffffffffffff111111111111111111111111111111111111111273ffffffffffffffffffffffffffffffffffffffff8216016124bb576124b67f0000000000000000000000000000000000000000000000000000000000000000476137bb565b612576565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526125769082907f00000000000000000000000000000000000000000000000000000000000000009073ffffffffffffffffffffffffffffffffffffffff8316906370a0823190602401602060405180830381865afa15801561254d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125719190614fa6565b613c80565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fdff2a3947bcf9fc0807b142e7c8497066db9183428b7bdbfb1fcd0f55c27a3df90600090a250600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167501000000000000000000000000000000000000000000179055565b6000611d49858585610daf565b6000610cb682612014565b600061261c612687565b73ffffffffffffffffffffffffffffffffffffffff8616330361266f576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e266004820152602401610c07565b61267c868a868686613405565b611554888888612c93565b6008547501000000000000000000000000000000000000000000900460ff166001146126e3576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e276004820152602401610c07565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167502000000000000000000000000000000000000000000179055565b6000610cb63483835b6040519080825280601f01601f191660200182016040528015612758576020820181803683370190505b50613d24565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f000000000000000000000000000000000000000000000000000000000000000060048201526000906128389073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063b5c736e490602401602060405180830381865afa15801561280f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128339190614fa6565b613e0b565b50919050565b600854600090819067ffffffffffffffff680100000000000000008204811691168085101561289d576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2b6004820152602401610c07565b600854600090760100000000000000000000000000000000000000000000900460ff16156129d457600754600090819073ffffffffffffffffffffffffffffffffffffffff16635776409464e8d4a510006128f760025490565b6129019089614ec5565b61290b9190614f0b565b6040518263ffffffff1660e01b815260040161292991815260200190565b606060405180830381865afa158015612946573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061296a9190615100565b9097509092509050652d79883d20008211806129835750855b1561298d57600091505b600854700100000000000000000000000000000000900464ffffffffff16818110156129b65750805b6301e133808142038402816129cd576129cd614edc565b0493505050505b81828703655af3107a400002816129ed576129ed614edc565b0401655af3107a4000612a008285614ec5565b612a0a9190614f0b565b612a149084614f93565b9450505050915091565b80821015612a5c576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e226004820152602401610c07565b5050565b6000827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0484118302158202612a9557600080fd5b5091020490565b73ffffffffffffffffffffffffffffffffffffffff8316612b3e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460448201527f72657373000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff8216612be1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f20616464726560448201527f73730000000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff83811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6000827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0484118302158202612c8457600080fd5b50910281810615159190040190565b6000610eb5848484614019565b73ffffffffffffffffffffffffffffffffffffffff8381166000908152600160209081526040808320938616835292905220547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114612d715781811015612d64576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610c07565b612d718484848403612a9c565b50505050565b73ffffffffffffffffffffffffffffffffffffffff8316612e1a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f20616460448201527f64726573730000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff8216612ebd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201527f65737300000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff831660009081526020819052604090205481811015612f73576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206260448201527f616c616e636500000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff848116600081815260208181526040808320878703905593871680835291849020805487019055925185815290927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3612d71565b60003073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001614801561304c57507f000000000000000000000000000000000000000000000000000000000000000046145b1561307657507f000000000000000000000000000000000000000000000000000000000000000090565b50604080517f00000000000000000000000000000000000000000000000000000000000000006020808301919091527f0000000000000000000000000000000000000000000000000000000000000000828401527f000000000000000000000000000000000000000000000000000000000000000060608301524660808301523060a0808401919091528351808403909101815260c0909201909252805191012090565b6000806131f867ffffffffffffffff60017f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663b5c736e47f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b81526004016131a691815260200190565b602060405180830381865afa1580156131c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131e79190614fa6565b901c16600860ff9082901c91161b90565b905064e8d4a5100061320861275e565b82028161321757613217614edc565b0491505090565b60008061322a8461283e565b6008549193509150760100000000000000000000000000000000000000000000900460ff16806132575750825b156133635767ffffffffffffffff8211156132a2576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e286004820152602401610c07565b6008805467ffffffffffffffff8681167fffffffffffffffffffffff00000000000000000000000000000000000000000090921668010000000000000000918616919091027fffffffffffffffffffffff0000000000ffffffffffffffff00000000000000001617177001000000000000000000000000000000004264ffffffffff160217905560408051838152602081018690527f9dd85e9767d796973b86c6ccf3a294429cfd5e3e93fa23ac388b9277bb8283fd910160405180910390a15b801561208257600880547fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff1690555092915050565b600080600083516041146133ab57600080fd5b5050506020810151604082015160609092015160001a92909190565b80821115612a5c576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e236004820152602401610c07565b600080600061344985858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061339892505050565b92509250925061345e88338989878787612089565b5050505050505050565b6000613475843084614019565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663d0e30db0856040518263ffffffff1660e01b81526004016000604051808303818588803b1580156134df57600080fd5b505af11580156134f3573d6000803e3d6000fd5b5050505050610d6f7f00000000000000000000000000000000000000000000000000000000000000008486613c80565b6040517f2520e7ff0000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1690632520e7ff90602401602060405180830381865afa1580156135ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135d19190615135565b61360b576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e256004820152602401610c07565b565b60006020825111156136e0576040517f36c7851600000000000000000000000000000000000000000000000000000000815233600482015230602482015273ffffffffffffffffffffffffffffffffffffffff80861660448301527f00000000000000000000000000000000000000000000000000000000000000001660648201526e22d473030f116ddee9f6b43ac78ba3906336c7851690608401600060405180830381600087803b1580156136c357600080fd5b505af11580156136d7573d6000803e3d6000fd5b5050505061370c565b61370c7f00000000000000000000000000000000000000000000000000000000000000003330876140bf565b6040517f2e1a7d4d000000000000000000000000000000000000000000000000000000008152600481018590527f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1690632e1a7d4d90602401600060405180830381600087803b15801561379457600080fd5b505af11580156137a8573d6000803e3d6000fd5b50610eb59250869150859050600061272e565b80471015613825576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e63650000006044820152606401610c07565b60008273ffffffffffffffffffffffffffffffffffffffff168260405160006040518083038185875af1925050503d806000811461387f576040519150601f19603f3d011682016040523d82523d6000602084013e613884565b606091505b5050905080613915576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603a60248201527f416464726573733a20756e61626c6520746f2073656e642076616c75652c207260448201527f6563697069656e74206d617920686176652072657665727465640000000000006064820152608401610c07565b505050565b60007f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ad967e158473eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee61397787614186565b6000806000896040518863ffffffff1660e01b815260040161399e96959493929190615150565b604080518083038185885af11580156139bb573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906139e091906151a9565b509392505050565b73ffffffffffffffffffffffffffffffffffffffff8116613a39576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e246004820152602401610c07565b50565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f00000000000000000000000000000000000000000000000000000000000000006004820152600090819073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063b5c736e490602401602060405180830381865afa158015613aeb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b0f9190614fa6565b9050600981901c66ffffffffffffff16600182901c60ff161b613b32828261423c565b92506000613b3e61275e565b64e8d4a51000948102859004949202919091049050828111613b61576000613b6b565b613b6b83826150dd565b925073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001631838111613bb25780613bb4565b835b935050505090565b73ffffffffffffffffffffffffffffffffffffffff81166000908152600560205260409020805460018101825590612838565b6000610cb6613bfc612fe6565b836040517f19010000000000000000000000000000000000000000000000000000000000006020820152602281018390526042810182905260009060620160405160208183030381529060405280519060200120905092915050565b6000806000613c69878787876142d0565b91509150613c76816143bf565b5095945050505050565b60006040517fa9059cbb00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff84166004820152826024820152602060006044836000895af13d15601f3d1160016000511416171691505080612d71576040517fdee51a8a0000000000000000000000000000000000000000000000000000000081526201155a6004820152602401610c07565b600082613d30816139e8565b6000613d3c868561391a565b9050613d4981600061321e565b905080613d5b64e8d4a5100088614ec5565b613d659190614f0b565b925082600003613da5576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e216004820152602401610c07565b613daf8584614572565b604080518781526020810185905273ffffffffffffffffffffffffffffffffffffffff87169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a350509392505050565b67ffffffffffffffff605b82901c811690609b83901c16811580613e2d575080155b15613e69576040517fd50d7512000000000000000000000000000000000000000000000000000000008152620111716004820152602401610c07565b61ffff8316603a84901c6401ffffffff16428181039160ea87901c617fff16911480613e93575082155b80613e9e5750806001145b15613eab57505050915091565b64496cebb80084840283020484019350617fff60db87901c16925082600103613ed657505050915091565b82600116600103613f2b5760019290921c91826c7e37be2022c0914b268000000081613f0457613f04614edc565b049250612710601e87901c613fff166b033b2e3c9fd0803ce8000000850102049250613f58565b60019290921c916305f5e100601e87901c613fff166127108501026b033b2e3c9fd0803ce8000000020492505b80600116600103613f8f5760011c61271081016b033b2e3c9fd0803ce8000000820281613f8757613f87614edc565b049050613fc5565b60011c61271081016b033b2e3c9fd0803ce8000000820281613fb357613fb3614edc565b046b033b2e3c9fd0803ce80000000390505b760a70c3c40a64e6c51999090b65f67d92400000000000008382026127100261ffff881691900402601087901c613fff16612710030292506801b5a660ea44b8000085840283020485019450505050915091565b600082614025816139e8565b61404864e8d4a5100061404061403961275e565b600061321e565b879190612c4f565b91506140548383614665565b61405e8585614829565b50604080518681526020810184905273ffffffffffffffffffffffffffffffffffffffff808616929087169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4509392505050565b60006040517f23b872dd00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516600482015273ffffffffffffffffffffffffffffffffffffffff841660248201528260448201526020600060648360008a5af13d15601f3d116001600051141617169150508061417f576040517fdee51a8a000000000000000000000000000000000000000000000000000000008152620115596004820152602401610c07565b5050505050565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff821115614238576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602860248201527f53616665436173743a2076616c756520646f65736e27742066697420696e206160448201527f6e20696e743235360000000000000000000000000000000000000000000000006064820152608401610c07565b5090565b600066ffffffffffffff604984901c1660ff604185901c161b808203614266576000915050610cb6565b612710613fff60a286901c168402046401ffffffff608186901c16420362ffffff60b087901c166142978284614ec5565b6142a19190614f0b565b90508083116142b15760006142b5565b8083035b935050808403838111156142c7578093505b50505092915050565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a083111561430757506000905060036143b6565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa15801561435b573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff81166143af576000600192509250506143b6565b9150600090505b94509492505050565b60008160048111156143d3576143d36151cd565b036143db5750565b60018160048111156143ef576143ef6151cd565b03614456576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401610c07565b600281600481111561446a5761446a6151cd565b036144d1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610c07565b60038160048111156144e5576144e56151cd565b03613a39576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c60448201527f75650000000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff82166145ef576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610c07565b80600260008282546146019190614f93565b909155505073ffffffffffffffffffffffffffffffffffffffff8216600081815260208181526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b73ffffffffffffffffffffffffffffffffffffffff8216614708576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360448201527f73000000000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff8216600090815260208190526040902054818110156147be576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60448201527f63650000000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff83166000818152602081815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b60007f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ad967e1573eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee61488586614186565b61488e906151fc565b60408051600080825260208201928390527fffffffff0000000000000000000000000000000000000000000000000000000060e087901b169092526148dd939291908890829060248101615150565b60408051808303816000875af11580156148fb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139e091906151a9565b73ffffffffffffffffffffffffffffffffffffffff81168114613a3957600080fd5b6000806040838503121561495457600080fd5b8235915060208301356149668161491f565b809150509250929050565b6000806040838503121561498457600080fd5b823561498f8161491f565b946020939093013593505050565b6000815180845260005b818110156149c3576020818501810151868301820152016149a7565b5060006020828601015260207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011685010191505092915050565b602081526000610d6f602083018461499d565b600060208284031215614a2657600080fd5b5035919050565b600080600060608486031215614a4257600080fd5b833592506020840135614a548161491f565b91506040840135614a648161491f565b809150509250925092565b600080600060608486031215614a8457600080fd5b8335614a8f8161491f565b92506020840135614a9f8161491f565b929592945050506040919091013590565b60008060008060808587031215614ac657600080fd5b843593506020850135614ad88161491f565b92506040850135614ae88161491f565b9396929550929360600135925050565b600060208284031215614b0a57600080fd5b8135610d6f8161491f565b60008083601f840112614b2757600080fd5b50813567ffffffffffffffff811115614b3f57600080fd5b602083019150836020828501011115614b5757600080fd5b9250929050565b60008060008060008060a08789031215614b7757600080fd5b863595506020870135614b898161491f565b94506040870135935060608701359250608087013567ffffffffffffffff811115614bb357600080fd5b614bbf89828a01614b15565b979a9699509497509295939492505050565b60008060008060008060008060e0898b031215614bed57600080fd5b88359750602089013596506040890135614c068161491f565b95506060890135614c168161491f565b94506080890135935060a0890135925060c089013567ffffffffffffffff811115614c4057600080fd5b614c4c8b828c01614b15565b999c989b5096995094979396929594505050565b600080600080600080868803610140811215614c7b57600080fd5b873596506020880135614c8d8161491f565b95506040880135945060c07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa082011215614cc657600080fd5b5060608701925061012087013567ffffffffffffffff811115614bb357600080fd5b600080600080600080600060c0888a031215614d0357600080fd5b873596506020880135614d158161491f565b95506040880135614d258161491f565b9450606088013593506080880135925060a088013567ffffffffffffffff811115614d4f57600080fd5b614d5b8a828b01614b15565b989b979a50959850939692959293505050565b600080600060608486031215614d8357600080fd5b833592506020840135614a9f8161491f565b60008060008060608587031215614dab57600080fd5b8435614db68161491f565b935060208501359250604085013567ffffffffffffffff811115614dd957600080fd5b614de587828801614b15565b95989497509550505050565b600080600080600080600060e0888a031215614e0c57600080fd5b8735614e178161491f565b96506020880135614e278161491f565b95506040880135945060608801359350608088013560ff81168114614e4b57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215614e7b57600080fd5b8235614e868161491f565b915060208301356149668161491f565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b8082028115828204841417610cb657610cb6614e96565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082614f41577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b500490565b600181811c90821680614f5a57607f821691505b602082108103612838577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b80820180821115610cb657610cb6614e96565b600060208284031215614fb857600080fd5b5051919050565b803565ffffffffffff81168114614fd557600080fd5b919050565b8183528181602085013750600060208284010152600060207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f840116840101905092915050565b600061010073ffffffffffffffffffffffffffffffffffffffff8088168452863561504d8161491f565b81811660208601525060208701356150648161491f565b81811660408601525061507960408801614fbf565b65ffffffffffff80821660608701528061509560608b01614fbf565b166080870152505060808701356150ab8161491f565b81811660a0860152505060a086013560c08401528060e08401526150d28184018587614fda565b979650505050505050565b81810381811115610cb657610cb6614e96565b80518015158114614fd557600080fd5b60008060006060848603121561511557600080fd5b83519250615125602085016150f0565b9150604084015190509250925092565b60006020828403121561514757600080fd5b610d6f826150f0565b600073ffffffffffffffffffffffffffffffffffffffff8089168352876020840152866040840152808616606084015280851660808401525060c060a083015261519d60c083018461499d565b98975050505050505050565b600080604083850312156151bc57600080fd5b505080516020909101519092909150565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b60007f8000000000000000000000000000000000000000000000000000000000000000820361522d5761522d614e96565b506000039056fea264697066735822122053470c3a57c2695b006bac4e3ad1eff7585b42a4b2e35348024fb3de22fcb9a264736f6c6343000815003300000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49700000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d03000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Deployed Bytecode
0x60806040526004361061038f5760003560e01c80637d7c2a1c116101dc578063ba08765211610102578063dd62ed3e116100a0578063e53b20171161006f578063e53b201714610b38578063eb26620c14610b58578063ef8b30f714610b78578063f5a35aaa14610b9857600080fd5b8063dd62ed3e14610a7d578063df2ebdbb14610ad0578063e083be2214610af8578063e359754814610b1857600080fd5b8063c6e6f592116100dc578063c6e6f592146109fd578063ce96cb7714610a1d578063d505accf14610a3d578063d905777e14610a5d57600080fd5b8063ba0876521461099d578063bc157ac1146109bd578063c63d75b6146109dd57600080fd5b80639f40a7b31161017a578063ad20750111610149578063ad2075011461091d578063b046a4491461093d578063b3d7f6b91461095d578063b460af941461097d57600080fd5b80639f40a7b31461089d578063a318c1a4146108bd578063a457c2d7146108dd578063a9059cbb146108fd57600080fd5b8063836a1040116101b6578063836a1040146108285780638c87483a1461084857806394bf804d1461086857806395d89b411461088857600080fd5b80637d7c2a1c146107ed5780637ecebe00146107f5578063805411871461081557600080fd5b806338d52e0f116102c157806341b3d1851161025f578063635c31c21161022e578063635c31c21461074a5780636e553f651461076a57806370a082311461078a578063740c955e146107cd57600080fd5b806341b3d185146106d35780634cdad506146106e857806350cc0f8f146107085780635fd619651461072857600080fd5b80633bc5de301161029b5780633bc5de30146105ea5780633c3821f4146106695780633f4c093014610693578063402d267d146106b357600080fd5b806338d52e0f1461055657806339509351146105aa5780633badef91146105ca57600080fd5b806318160ddd1161032e5780632ae06214116103085780632ae06214146104d0578063313ce567146104f057806333bb7f911461052e5780633644e5151461054157600080fd5b806318160ddd1461047b5780632126e91e1461049057806323b872dd146104b057600080fd5b806306fdde031161036a57806306fdde03146103e957806307a2d13a1461040b578063095ea7b31461042b5780630a28a4771461045b57600080fd5b8062acb7361461039b57806301e1d114146103c157806302279b4a146103d657600080fd5b3661039657005b600080fd5b6103ae6103a9366004614941565b610bb8565b6040519081526020015b60405180910390f35b3480156103cd57600080fd5b506103ae610c60565b6103ae6103e4366004614971565b610c9f565b3480156103f557600080fd5b506103fe610cbc565b6040516103b89190614a01565b34801561041757600080fd5b506103ae610426366004614a14565b610d4e565b34801561043757600080fd5b5061044b610446366004614971565b610d76565b60405190151581526020016103b8565b34801561046757600080fd5b506103ae610476366004614a14565b610d8e565b34801561048757600080fd5b506002546103ae565b34801561049c57600080fd5b506103ae6104ab366004614a2d565b610daf565b3480156104bc57600080fd5b5061044b6104cb366004614a6f565b610e78565b3480156104dc57600080fd5b506103ae6104eb366004614ab0565b610e9c565b3480156104fc57600080fd5b5060405160ff7f00000000000000000000000000000000000000000000000000000000000000121681526020016103b8565b6103ae61053c366004614af8565b610ebd565b34801561054d57600080fd5b506103ae610f16565b34801561056257600080fd5b507f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016103b8565b3480156105b657600080fd5b5061044b6105c5366004614971565b610f25565b3480156105d657600080fd5b506103ae6105e5366004614a2d565b610f71565b3480156105f657600080fd5b506105ff61103f565b6040805173ffffffffffffffffffffffffffffffffffffffff9a8b168152988a1660208a0152968916968801969096529387166060870152959091166080850152151560a084015260c083019390935260e0820192909252610100810191909152610120016103b8565b34801561067557600080fd5b5061067e61112b565b604080519283526020830191909152016103b8565b34801561069f57600080fd5b506103ae6106ae366004614b5e565b611149565b3480156106bf57600080fd5b506103ae6106ce366004614af8565b61128f565b3480156106df57600080fd5b506103ae6113d3565b3480156106f457600080fd5b506103ae610703366004614a14565b6114d4565b34801561071457600080fd5b506103ae610723366004614bd1565b6114df565b34801561073457600080fd5b50610748610743366004614af8565b6115b7565b005b34801561075657600080fd5b506103ae610765366004614c60565b61167d565b34801561077657600080fd5b506103ae610785366004614941565b611793565b34801561079657600080fd5b506103ae6107a5366004614af8565b73ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b3480156107d957600080fd5b506103ae6107e8366004614ce8565b61188d565b6103ae611972565b34801561080157600080fd5b506103ae610810366004614af8565b611ab7565b6103ae610823366004614d6e565b611ae2565b34801561083457600080fd5b506103ae610843366004614d6e565b611afa565b34801561085457600080fd5b506103ae610863366004614c60565b611b06565b34801561087457600080fd5b506103ae610883366004614941565b611c16565b34801561089457600080fd5b506103fe611d20565b3480156108a957600080fd5b506103ae6108b8366004614ab0565b611d2f565b3480156108c957600080fd5b506103ae6108d8366004614ab0565b611d3c565b3480156108e957600080fd5b5061044b6108f8366004614971565b611d55565b34801561090957600080fd5b5061044b610918366004614971565b611e26565b34801561092957600080fd5b50610748610938366004614d95565b611e34565b34801561094957600080fd5b50610748610958366004614af8565b611e6a565b34801561096957600080fd5b506103ae610978366004614a14565b611eec565b34801561098957600080fd5b506103ae610998366004614a2d565b611f0d565b3480156109a957600080fd5b506103ae6109b8366004614a2d565b611f7b565b3480156109c957600080fd5b506103ae6109d8366004614d6e565b611fed565b3480156109e957600080fd5b506103ae6109f8366004614af8565b612005565b348015610a0957600080fd5b506103ae610a18366004614a14565b612014565b348015610a2957600080fd5b506103ae610a38366004614af8565b612035565b348015610a4957600080fd5b50610748610a58366004614df1565b612089565b348015610a6957600080fd5b506103ae610a78366004614af8565b612248565b348015610a8957600080fd5b506103ae610a98366004614e68565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260016020908152604080832093909416825291909152205490565b348015610adc57600080fd5b5061058573eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b348015610b0457600080fd5b506103ae610b13366004614b5e565b612286565b348015610b2457600080fd5b506103ae610b33366004614ce8565b6123b3565b348015610b4457600080fd5b50610748610b53366004614af8565b61243f565b348015610b6457600080fd5b506103ae610b73366004614ab0565b6125fa565b348015610b8457600080fd5b506103ae610b93366004614a14565b612607565b348015610ba457600080fd5b506103ae610bb3366004614bd1565b612612565b6000610bc2612687565b610bcb83611eec565b905080341015610c10576040517f694bda1d00000000000000000000000000000000000000000000000000000000815261520960048201526024015b60405180910390fd5b610c1982612725565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905592915050565b600080610c73610c6e61275e565b61283e565b50905064e8d4a51000610c8560025490565b610c8f9083614ec5565b610c999190614f0b565b91505090565b6000610caa83610ebd565b9050610cb68183612a1e565b92915050565b606060038054610ccb90614f46565b80601f0160208091040260200160405190810160405280929190818152602001828054610cf790614f46565b8015610d445780601f10610d1957610100808354040283529160200191610d44565b820191906000526020600020905b815481529060010190602001808311610d2757829003601f168201915b5050505050905090565b600080610d5c610c6e61275e565b509050610d6f838264e8d4a51000612a60565b9392505050565b600033610d84818585612a9c565b5060019392505050565b600080610d9c610c6e61275e565b509050610d6f8364e8d4a5100083612c4f565b6000610db9612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403610dfc5733600090815260208190526040902054610df9906114d4565b93505b610e07848484612c93565b90503373ffffffffffffffffffffffffffffffffffffffff831614610e3157610e31823383612ca0565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559392505050565b600033610e86858285612ca0565b610e91858585612d77565b506001949350505050565b6000610ea9858585610f71565b9050610eb58183612a1e565b949350505050565b6000610ec7612687565b610ed082612725565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905592915050565b6000610f20612fe6565b905090565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff87168452909152812054909190610d849082908690610f6c908790614f93565b612a9c565b6000610f7b612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403610fb5573360009081526020819052604090205493505b610fbe846114d4565b90506000610fcd828585612c93565b90503373ffffffffffffffffffffffffffffffffffffffff841614610ff757610ff7833383612ca0565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559392505050565b600080600080600080600080600061105561275e565b915060006110628361283e565b6007546009546008549395509193507f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497927f00000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d039273ffffffffffffffffffffffffffffffffffffffff928316926e22d473030f116ddee9f6b43ac78ba392911690760100000000000000000000000000000000000000000000900460ff168015611109575085155b61111161311a565b995099509950995099509950995050909192939495969798565b60008061113661275e565b905061114381600161321e565b91509091565b600061115487611eec565b9050600080600061119a86868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061339892505050565b6040517fd505accf00000000000000000000000000000000000000000000000000000000815233600482015230602482015260448101889052606481018b905260ff8416608482015260a4810183905260c48101829052929550909350915073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2169063d505accf9060e401600060405180830381600087803b15801561125457600080fd5b505af1158015611268573d6000803e3d6000fd5b505050506112768a8a611c16565b935061128284896133c7565b5050509695505050505050565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527fb2084a3e4595ccf007fb44245853374aaf0de960074375e8e0fb334712e94d0e6004820152600090819067ffffffffffffffff9073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497169063b5c736e490602401602060405180830381865afa158015611348573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061136c9190614fa6565b16600881901c60ff9091161b905064e8d4a5100061138861275e565b82028161139757611397614edc565b0490506f7fffffffffffff7fffffffffffffffff8111156113bb5750600092915050565b6f7fffffffffffffffffffffffffffffff0392915050565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527fb2084a3e4595ccf007fb44245853374aaf0de960074375e8e0fb334712e94d0e6004820152600090819060ff9073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497169063b5c736e490602401602060405180830381865afa158015611485573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114a99190614fa6565b166001901b905060006114bc6001611eec565b90508082116114cb57806114cd565b815b9250505090565b6000610cb682610d4e565b60006114e9612687565b73ffffffffffffffffffffffffffffffffffffffff8616330361153c576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e266004820152602401610c07565b611549868a868686613405565b611554888888613468565b905061156081866133c7565b61156b863383612ca0565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905598975050505050505050565b6115bf613523565b6115c761112b565b5050600780547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff8316908117909155600880547fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff16821515760100000000000000000000000000000000000000000000021790556040517fd14b198a72267efb36b8bbc193eb6d52a00d1f61799029250f6a520ad47be82d90600090a250565b6000611687612687565b6040517f2b67b5700000000000000000000000000000000000000000000000000000000081526e22d473030f116ddee9f6b43ac78ba390632b67b570906116d8903390889088908890600401615023565b600060405180830381600087803b1580156116f257600080fd5b505af1158015611706573d6000803e3d6000fd5b50506040805160016020820152339181019190915261173d925089915088906060015b60405160208183030381529060405261360d565b90506117498186612a1e565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559695505050505050565b600061179d612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8303611875576040517f70a082310000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273ffffffffffffffffffffffffffffffffffffffff16906370a0823190602401602060405180830381865afa15801561184e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118729190614fa6565b92505b60408051336020820152610e31918591859101611729565b6000611897612687565b73ffffffffffffffffffffffffffffffffffffffff861633036118ea576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e266004820152602401610c07565b6118f3886114d4565b90506118ff8186612a1e565b61190c8689868686613405565b6000611919828989613468565b9050611926873383612ca0565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167501000000000000000000000000000000000000000000179055979650505050505050565b600061197c612687565b60095473ffffffffffffffffffffffffffffffffffffffff1633146119d1576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e296004820152602401610c07565b6119d961311a565b6119e1610c60565b6119eb91906150dd565b9050803410156119fc575034611a17565b80341115611a1757611a1733611a1283346150dd565b6137bb565b60408051600080825260208201909252611a3290839061391a565b9050611a3f81600161321e565b506040518281527fe97ad8b810ae9d9e29aa69dc04d4ac2e3e71d65307830ccb97c8f876dfc439319060200160405180910390a150600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905590565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260056020526040812054610cb6565b6000611aee8484610bb8565b9050610d6f81836133c7565b6000611aee8484611c16565b6000611b10612687565b611b1987611eec565b9050611b2581866133c7565b6040517f2b67b5700000000000000000000000000000000000000000000000000000000081526e22d473030f116ddee9f6b43ac78ba390632b67b57090611b76903390889088908890600401615023565b600060405180830381600087803b158015611b9057600080fd5b505af1158015611ba4573d6000803e3d6000fd5b505060408051600160208201523391810191909152611bcb92508391508890606001611729565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559695505050505050565b6000611c20612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8303611cfc576040517f70a082310000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273ffffffffffffffffffffffffffffffffffffffff16906370a0823190602401602060405180830381865afa158015611cd1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cf59190614fa6565b9050611d08565b611d0583611eec565b90505b60408051336020820152610c19918391859101611729565b606060048054610ccb90614f46565b6000610ea9858585611f7b565b6000611d49858585611f0d565b9050610eb581836133c7565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8716845290915281205490919083811015611e19576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7760448201527f207a65726f0000000000000000000000000000000000000000000000000000006064820152608401610c07565b610e918286868403612a9c565b600033610d84818585612d77565b6040517f694bda1d00000000000000000000000000000000000000000000000000000000815261520a6004820152602401610c07565b80611e74816139e8565b611e7c613523565b600980547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff84169081179091556040517fdb94ee7fd8b5bbf8f6d59e76731ff4b4f5a02ab3af1d3e0c774862cf96ff613b90600090a25050565b600080611efa610c6e61275e565b509050610d6f838264e8d4a51000612c4f565b6000611f17612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403611f7057611f6d6107038373ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b93505b610e07848484613468565b6000611f85612687565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403611fd55773ffffffffffffffffffffffffffffffffffffffff821660009081526020819052604090205493505b611fde846114d4565b90506000610fcd828585613468565b6000611ff98484611793565b9050610d6f8183612a1e565b6000610cb6610a18600061128f565b600080612022610c6e61275e565b509050610d6f8364e8d4a5100083612a60565b600080612040613a3c565b905060006120736104268573ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b90508082106120825780610eb5565b5092915050565b834211156120f3576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606401610c07565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886121228c613bbc565b60408051602081019690965273ffffffffffffffffffffffffffffffffffffffff94851690860152929091166060840152608083015260a082015260c0810186905260e001604051602081830303815290604052805190602001209050600061218a82613bef565b9050600061219a82878787613c58565b90508973ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614612231576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152606401610c07565b61223c8a8a8a612a9c565b50505050505050505050565b600080612256610a18613a3c565b905060006120738473ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b6000806000806122cb86868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061339892505050565b6040517fd505accf000000000000000000000000000000000000000000000000000000008152336004820152306024820152604481018e9052606481018b905260ff8416608482015260a4810183905260c48101829052929550909350915073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2169063d505accf9060e401600060405180830381600087803b15801561238557600080fd5b505af1158015612399573d6000803e3d6000fd5b505050506123a78a8a611793565b93506112828489612a1e565b60006123bd612687565b73ffffffffffffffffffffffffffffffffffffffff86163303612410576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e266004820152602401610c07565b612419886114d4565b90506124258186612a1e565b6124328689868686613405565b6000611919828989612c93565b612447612687565b61244f613523565b7fffffffffffffffffffffffff111111111111111111111111111111111111111273ffffffffffffffffffffffffffffffffffffffff8216016124bb576124b67f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497476137bb565b612576565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526125769082907f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e4979073ffffffffffffffffffffffffffffffffffffffff8316906370a0823190602401602060405180830381865afa15801561254d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125719190614fa6565b613c80565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fdff2a3947bcf9fc0807b142e7c8497066db9183428b7bdbfb1fcd0f55c27a3df90600090a250600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167501000000000000000000000000000000000000000000179055565b6000611d49858585610daf565b6000610cb682612014565b600061261c612687565b73ffffffffffffffffffffffffffffffffffffffff8616330361266f576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e266004820152602401610c07565b61267c868a868686613405565b611554888888612c93565b6008547501000000000000000000000000000000000000000000900460ff166001146126e3576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e276004820152602401610c07565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167502000000000000000000000000000000000000000000179055565b6000610cb63483835b6040519080825280601f01601f191660200182016040528015612758576020820181803683370190505b50613d24565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527fa1829a9003092132f585b6ccdd167c19fe9774dbdea4260287e8a8e8ca8185d760048201526000906128389073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497169063b5c736e490602401602060405180830381865afa15801561280f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128339190614fa6565b613e0b565b50919050565b600854600090819067ffffffffffffffff680100000000000000008204811691168085101561289d576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2b6004820152602401610c07565b600854600090760100000000000000000000000000000000000000000000900460ff16156129d457600754600090819073ffffffffffffffffffffffffffffffffffffffff16635776409464e8d4a510006128f760025490565b6129019089614ec5565b61290b9190614f0b565b6040518263ffffffff1660e01b815260040161292991815260200190565b606060405180830381865afa158015612946573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061296a9190615100565b9097509092509050652d79883d20008211806129835750855b1561298d57600091505b600854700100000000000000000000000000000000900464ffffffffff16818110156129b65750805b6301e133808142038402816129cd576129cd614edc565b0493505050505b81828703655af3107a400002816129ed576129ed614edc565b0401655af3107a4000612a008285614ec5565b612a0a9190614f0b565b612a149084614f93565b9450505050915091565b80821015612a5c576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e226004820152602401610c07565b5050565b6000827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0484118302158202612a9557600080fd5b5091020490565b73ffffffffffffffffffffffffffffffffffffffff8316612b3e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460448201527f72657373000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff8216612be1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f20616464726560448201527f73730000000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff83811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6000827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0484118302158202612c8457600080fd5b50910281810615159190040190565b6000610eb5848484614019565b73ffffffffffffffffffffffffffffffffffffffff8381166000908152600160209081526040808320938616835292905220547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114612d715781811015612d64576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610c07565b612d718484848403612a9c565b50505050565b73ffffffffffffffffffffffffffffffffffffffff8316612e1a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f20616460448201527f64726573730000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff8216612ebd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201527f65737300000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff831660009081526020819052604090205481811015612f73576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206260448201527f616c616e636500000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff848116600081815260208181526040808320878703905593871680835291849020805487019055925185815290927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3612d71565b60003073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000090551c1795392094fe6d29b758eccd233cfaa2601614801561304c57507f000000000000000000000000000000000000000000000000000000000000000146145b1561307657507f1239c74e11526798e3b620684285697e6e1cdbf6d299991f3b7ccb279fe6f42a90565b50604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f6020808301919091527f675c9f483a21ef057164c8e363f71060b2370f0686a71f7c0b56e68be74db438828401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608301524660808301523060a0808401919091528351808403909101815260c0909201909252805191012090565b6000806131f867ffffffffffffffff60017f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49773ffffffffffffffffffffffffffffffffffffffff1663b5c736e47f90cafdc9ecf72fa76b78e674a1810648dc2af69013668e62131e7d290483cdc46040518263ffffffff1660e01b81526004016131a691815260200190565b602060405180830381865afa1580156131c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131e79190614fa6565b901c16600860ff9082901c91161b90565b905064e8d4a5100061320861275e565b82028161321757613217614edc565b0491505090565b60008061322a8461283e565b6008549193509150760100000000000000000000000000000000000000000000900460ff16806132575750825b156133635767ffffffffffffffff8211156132a2576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e286004820152602401610c07565b6008805467ffffffffffffffff8681167fffffffffffffffffffffff00000000000000000000000000000000000000000090921668010000000000000000918616919091027fffffffffffffffffffffff0000000000ffffffffffffffff00000000000000001617177001000000000000000000000000000000004264ffffffffff160217905560408051838152602081018690527f9dd85e9767d796973b86c6ccf3a294429cfd5e3e93fa23ac388b9277bb8283fd910160405180910390a15b801561208257600880547fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff1690555092915050565b600080600083516041146133ab57600080fd5b5050506020810151604082015160609092015160001a92909190565b80821115612a5c576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e236004820152602401610c07565b600080600061344985858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061339892505050565b92509250925061345e88338989878787612089565b5050505050505050565b6000613475843084614019565b90507f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273ffffffffffffffffffffffffffffffffffffffff1663d0e30db0856040518263ffffffff1660e01b81526004016000604051808303818588803b1580156134df57600080fd5b505af11580156134f3573d6000803e3d6000fd5b5050505050610d6f7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28486613c80565b6040517f2520e7ff0000000000000000000000000000000000000000000000000000000081523360048201527f00000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d0373ffffffffffffffffffffffffffffffffffffffff1690632520e7ff90602401602060405180830381865afa1580156135ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135d19190615135565b61360b576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e256004820152602401610c07565b565b60006020825111156136e0576040517f36c7851600000000000000000000000000000000000000000000000000000000815233600482015230602482015273ffffffffffffffffffffffffffffffffffffffff80861660448301527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21660648201526e22d473030f116ddee9f6b43ac78ba3906336c7851690608401600060405180830381600087803b1580156136c357600080fd5b505af11580156136d7573d6000803e3d6000fd5b5050505061370c565b61370c7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc23330876140bf565b6040517f2e1a7d4d000000000000000000000000000000000000000000000000000000008152600481018590527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273ffffffffffffffffffffffffffffffffffffffff1690632e1a7d4d90602401600060405180830381600087803b15801561379457600080fd5b505af11580156137a8573d6000803e3d6000fd5b50610eb59250869150859050600061272e565b80471015613825576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e63650000006044820152606401610c07565b60008273ffffffffffffffffffffffffffffffffffffffff168260405160006040518083038185875af1925050503d806000811461387f576040519150601f19603f3d011682016040523d82523d6000602084013e613884565b606091505b5050905080613915576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603a60248201527f416464726573733a20756e61626c6520746f2073656e642076616c75652c207260448201527f6563697069656e74206d617920686176652072657665727465640000000000006064820152608401610c07565b505050565b60007f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49773ffffffffffffffffffffffffffffffffffffffff1663ad967e158473eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee61397787614186565b6000806000896040518863ffffffff1660e01b815260040161399e96959493929190615150565b604080518083038185885af11580156139bb573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906139e091906151a9565b509392505050565b73ffffffffffffffffffffffffffffffffffffffff8116613a39576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e246004820152602401610c07565b50565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f90cafdc9ecf72fa76b78e674a1810648dc2af69013668e62131e7d290483cdc46004820152600090819073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497169063b5c736e490602401602060405180830381865afa158015613aeb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b0f9190614fa6565b9050600981901c66ffffffffffffff16600182901c60ff161b613b32828261423c565b92506000613b3e61275e565b64e8d4a51000948102859004949202919091049050828111613b61576000613b6b565b613b6b83826150dd565b925073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e4971631838111613bb25780613bb4565b835b935050505090565b73ffffffffffffffffffffffffffffffffffffffff81166000908152600560205260409020805460018101825590612838565b6000610cb6613bfc612fe6565b836040517f19010000000000000000000000000000000000000000000000000000000000006020820152602281018390526042810182905260009060620160405160208183030381529060405280519060200120905092915050565b6000806000613c69878787876142d0565b91509150613c76816143bf565b5095945050505050565b60006040517fa9059cbb00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff84166004820152826024820152602060006044836000895af13d15601f3d1160016000511416171691505080612d71576040517fdee51a8a0000000000000000000000000000000000000000000000000000000081526201155a6004820152602401610c07565b600082613d30816139e8565b6000613d3c868561391a565b9050613d4981600061321e565b905080613d5b64e8d4a5100088614ec5565b613d659190614f0b565b925082600003613da5576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e216004820152602401610c07565b613daf8584614572565b604080518781526020810185905273ffffffffffffffffffffffffffffffffffffffff87169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a350509392505050565b67ffffffffffffffff605b82901c811690609b83901c16811580613e2d575080155b15613e69576040517fd50d7512000000000000000000000000000000000000000000000000000000008152620111716004820152602401610c07565b61ffff8316603a84901c6401ffffffff16428181039160ea87901c617fff16911480613e93575082155b80613e9e5750806001145b15613eab57505050915091565b64496cebb80084840283020484019350617fff60db87901c16925082600103613ed657505050915091565b82600116600103613f2b5760019290921c91826c7e37be2022c0914b268000000081613f0457613f04614edc565b049250612710601e87901c613fff166b033b2e3c9fd0803ce8000000850102049250613f58565b60019290921c916305f5e100601e87901c613fff166127108501026b033b2e3c9fd0803ce8000000020492505b80600116600103613f8f5760011c61271081016b033b2e3c9fd0803ce8000000820281613f8757613f87614edc565b049050613fc5565b60011c61271081016b033b2e3c9fd0803ce8000000820281613fb357613fb3614edc565b046b033b2e3c9fd0803ce80000000390505b760a70c3c40a64e6c51999090b65f67d92400000000000008382026127100261ffff881691900402601087901c613fff16612710030292506801b5a660ea44b8000085840283020485019450505050915091565b600082614025816139e8565b61404864e8d4a5100061404061403961275e565b600061321e565b879190612c4f565b91506140548383614665565b61405e8585614829565b50604080518681526020810184905273ffffffffffffffffffffffffffffffffffffffff808616929087169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4509392505050565b60006040517f23b872dd00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516600482015273ffffffffffffffffffffffffffffffffffffffff841660248201528260448201526020600060648360008a5af13d15601f3d116001600051141617169150508061417f576040517fdee51a8a000000000000000000000000000000000000000000000000000000008152620115596004820152602401610c07565b5050505050565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff821115614238576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602860248201527f53616665436173743a2076616c756520646f65736e27742066697420696e206160448201527f6e20696e743235360000000000000000000000000000000000000000000000006064820152608401610c07565b5090565b600066ffffffffffffff604984901c1660ff604185901c161b808203614266576000915050610cb6565b612710613fff60a286901c168402046401ffffffff608186901c16420362ffffff60b087901c166142978284614ec5565b6142a19190614f0b565b90508083116142b15760006142b5565b8083035b935050808403838111156142c7578093505b50505092915050565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a083111561430757506000905060036143b6565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa15801561435b573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff81166143af576000600192509250506143b6565b9150600090505b94509492505050565b60008160048111156143d3576143d36151cd565b036143db5750565b60018160048111156143ef576143ef6151cd565b03614456576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401610c07565b600281600481111561446a5761446a6151cd565b036144d1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610c07565b60038160048111156144e5576144e56151cd565b03613a39576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c60448201527f75650000000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff82166145ef576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610c07565b80600260008282546146019190614f93565b909155505073ffffffffffffffffffffffffffffffffffffffff8216600081815260208181526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b73ffffffffffffffffffffffffffffffffffffffff8216614708576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360448201527f73000000000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff8216600090815260208190526040902054818110156147be576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60448201527f63650000000000000000000000000000000000000000000000000000000000006064820152608401610c07565b73ffffffffffffffffffffffffffffffffffffffff83166000818152602081815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b60007f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49773ffffffffffffffffffffffffffffffffffffffff1663ad967e1573eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee61488586614186565b61488e906151fc565b60408051600080825260208201928390527fffffffff0000000000000000000000000000000000000000000000000000000060e087901b169092526148dd939291908890829060248101615150565b60408051808303816000875af11580156148fb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139e091906151a9565b73ffffffffffffffffffffffffffffffffffffffff81168114613a3957600080fd5b6000806040838503121561495457600080fd5b8235915060208301356149668161491f565b809150509250929050565b6000806040838503121561498457600080fd5b823561498f8161491f565b946020939093013593505050565b6000815180845260005b818110156149c3576020818501810151868301820152016149a7565b5060006020828601015260207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011685010191505092915050565b602081526000610d6f602083018461499d565b600060208284031215614a2657600080fd5b5035919050565b600080600060608486031215614a4257600080fd5b833592506020840135614a548161491f565b91506040840135614a648161491f565b809150509250925092565b600080600060608486031215614a8457600080fd5b8335614a8f8161491f565b92506020840135614a9f8161491f565b929592945050506040919091013590565b60008060008060808587031215614ac657600080fd5b843593506020850135614ad88161491f565b92506040850135614ae88161491f565b9396929550929360600135925050565b600060208284031215614b0a57600080fd5b8135610d6f8161491f565b60008083601f840112614b2757600080fd5b50813567ffffffffffffffff811115614b3f57600080fd5b602083019150836020828501011115614b5757600080fd5b9250929050565b60008060008060008060a08789031215614b7757600080fd5b863595506020870135614b898161491f565b94506040870135935060608701359250608087013567ffffffffffffffff811115614bb357600080fd5b614bbf89828a01614b15565b979a9699509497509295939492505050565b60008060008060008060008060e0898b031215614bed57600080fd5b88359750602089013596506040890135614c068161491f565b95506060890135614c168161491f565b94506080890135935060a0890135925060c089013567ffffffffffffffff811115614c4057600080fd5b614c4c8b828c01614b15565b999c989b5096995094979396929594505050565b600080600080600080868803610140811215614c7b57600080fd5b873596506020880135614c8d8161491f565b95506040880135945060c07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa082011215614cc657600080fd5b5060608701925061012087013567ffffffffffffffff811115614bb357600080fd5b600080600080600080600060c0888a031215614d0357600080fd5b873596506020880135614d158161491f565b95506040880135614d258161491f565b9450606088013593506080880135925060a088013567ffffffffffffffff811115614d4f57600080fd5b614d5b8a828b01614b15565b989b979a50959850939692959293505050565b600080600060608486031215614d8357600080fd5b833592506020840135614a9f8161491f565b60008060008060608587031215614dab57600080fd5b8435614db68161491f565b935060208501359250604085013567ffffffffffffffff811115614dd957600080fd5b614de587828801614b15565b95989497509550505050565b600080600080600080600060e0888a031215614e0c57600080fd5b8735614e178161491f565b96506020880135614e278161491f565b95506040880135945060608801359350608088013560ff81168114614e4b57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215614e7b57600080fd5b8235614e868161491f565b915060208301356149668161491f565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b8082028115828204841417610cb657610cb6614e96565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082614f41577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b500490565b600181811c90821680614f5a57607f821691505b602082108103612838577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b80820180821115610cb657610cb6614e96565b600060208284031215614fb857600080fd5b5051919050565b803565ffffffffffff81168114614fd557600080fd5b919050565b8183528181602085013750600060208284010152600060207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f840116840101905092915050565b600061010073ffffffffffffffffffffffffffffffffffffffff8088168452863561504d8161491f565b81811660208601525060208701356150648161491f565b81811660408601525061507960408801614fbf565b65ffffffffffff80821660608701528061509560608b01614fbf565b166080870152505060808701356150ab8161491f565b81811660a0860152505060a086013560c08401528060e08401526150d28184018587614fda565b979650505050505050565b81810381811115610cb657610cb6614e96565b80518015158114614fd557600080fd5b60008060006060848603121561511557600080fd5b83519250615125602085016150f0565b9150604084015190509250925092565b60006020828403121561514757600080fd5b610d6f826150f0565b600073ffffffffffffffffffffffffffffffffffffffff8089168352876020840152866040840152808616606084015280851660808401525060c060a083015261519d60c083018461499d565b98975050505050505050565b600080604083850312156151bc57600080fd5b505080516020909101519092909150565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b60007f8000000000000000000000000000000000000000000000000000000000000000820361522d5761522d614e96565b506000039056fea264697066735822122053470c3a57c2695b006bac4e3ad1eff7585b42a4b2e35348024fb3de22fcb9a264736f6c63430008150033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49700000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d03000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
-----Decoded View---------------
Arg [0] : liquidity_ (address): 0x52Aa899454998Be5b000Ad077a46Bbe360F4e497
Arg [1] : lendingFactory_ (address): 0x54B91A0D94cb471F37f949c60F7Fa7935b551D03
Arg [2] : weth_ (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497
Arg [1] : 00000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d03
Arg [2] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.