Overview
Max Total Supply
33,662.633574694140435055 LQIDETHFIV1
Holders
7,379 ( -0.081%)
Market
Onchain Market Cap
$0.00
Circulating Supply Market Cap
-
Other Info
Token Contract (WITH 18 Decimals)
Balance
0.249220972304158328 LQIDETHFIV1Value
$0.00Loading...
Loading
Loading...
Loading
Loading...
Loading
# | Exchange | Pair | Price | 24H Volume | % Volume |
---|
Contract Name:
CellarWithOracleWithBalancerFlashLoansWithMultiAssetDepositWithNativeSupport
Compiler Version
v0.8.21+commit.d9974bed
Optimization Enabled:
Yes with 200 runs
Other Settings:
shanghai EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import { Registry, ERC20, Math, SafeTransferLib, Address } from "src/base/Cellar.sol"; import { CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit } from "src/base/permutations/advanced/CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit.sol"; contract CellarWithOracleWithBalancerFlashLoansWithMultiAssetDepositWithNativeSupport is CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit { //============================== IMMUTABLES =============================== constructor( address _owner, Registry _registry, ERC20 _asset, string memory _name, string memory _symbol, uint32 _holdingPosition, bytes memory _holdingPositionConfig, uint256 _initialDeposit, uint64 _strategistPlatformCut, uint192 _shareSupplyCap, address _balancerVault ) CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit( _owner, _registry, _asset, _name, _symbol, _holdingPosition, _holdingPositionConfig, _initialDeposit, _strategistPlatformCut, _shareSupplyCap, _balancerVault ) {} /** * @notice Implement receive so Cellar can accept native transfers. */ receive() external payable {} }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import {Math} from "src/utils/Math.sol"; import {ERC4626} from "@solmate/mixins/ERC4626.sol"; import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol"; import {ERC20} from "@solmate/tokens/ERC20.sol"; // import { ERC4626, SafeTransferLib, Math, ERC20 } from "src/base/ERC4626.sol"; import {Registry} from "src/Registry.sol"; import {PriceRouter} from "src/modules/price-router/PriceRouter.sol"; import {Uint32Array} from "src/utils/Uint32Array.sol"; import {BaseAdaptor} from "src/modules/adaptors/BaseAdaptor.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import {Auth, Authority} from "@solmate/auth/Auth.sol"; /** * @title Sommelier Cellar * @notice A composable ERC4626 that can use arbitrary DeFi assets/positions using adaptors. * @author crispymangoes */ contract Cellar is ERC4626, Auth, ERC721Holder { using Uint32Array for uint32[]; using SafeTransferLib for ERC20; using Math for uint256; using Address for address; // ========================================= One Slot Values ========================================= // Below values are frequently accessed in the same TXs. By moving them to the top // they will be stored in the same slot, reducing cold access reads. /** * @notice The maximum amount of shares that can be in circulation. * @dev Can be decreased by the strategist. * @dev Can be increased by Sommelier Governance. */ uint192 public shareSupplyCap; /** * @notice `locked` is public, so that the state can be checked even during view function calls. */ bool public locked; /** * @notice Whether or not the contract is shutdown in case of an emergency. */ bool public isShutdown; /** * @notice Pauses all user entry/exits, and strategist rebalances. */ bool public ignorePause; /** * @notice This bool is used to stop strategists from abusing Base Adaptor functions(deposit/withdraw). */ bool public blockExternalReceiver; /** * @notice Stores the position id of the holding position in the creditPositions array. */ uint32 public holdingPosition; // ========================================= MULTICALL ========================================= /** * @notice Allows caller to call multiple functions in a single TX. * @dev Does NOT return the function return values. */ function multicall(bytes[] calldata data) external { for (uint256 i = 0; i < data.length; i++) { address(this).functionDelegateCall(data[i]); } } // ========================================= REENTRANCY GUARD ========================================= modifier nonReentrant() { require(!locked, "REENTRANCY"); locked = true; _; locked = false; } // ========================================= _isAuthorized ======================================== function _isAuthorized() internal requiresAuth {} // ========================================= PRICE ROUTER CACHE ========================================= /** * @notice Cached price router contract. * @dev This way cellar has to "opt in" to price router changes. */ PriceRouter public priceRouter; /** * @notice Updates the cellar to use the lastest price router in the registry. * @param checkTotalAssets If true totalAssets is checked before and after updating the price router, * and is verified to be withing a +- 5% envelope. * If false totalAssets is only called after updating the price router.] * @param allowableRange The +- range the total assets may deviate between the old and new price router. * - 1_000 == 10% * - 500 == 5% * @param expectedPriceRouter The registry price router differed from the expected price router. * @dev `allowableRange` reverts from arithmetic underflow if it is greater than 10_000, this is * desired behavior. * @dev Callable by Sommelier Governance. */ function cachePriceRouter(bool checkTotalAssets, uint16 allowableRange, address expectedPriceRouter) external { _isAuthorized(); uint256 minAssets; uint256 maxAssets; if (checkTotalAssets) { uint256 assetsBefore = totalAssets(); minAssets = assetsBefore.mulDivDown(1e4 - allowableRange, 1e4); maxAssets = assetsBefore.mulDivDown(1e4 + allowableRange, 1e4); } // Make sure expected price router is equal to price router grabbed from registry. _checkRegistryAddressAgainstExpected(PRICE_ROUTER_REGISTRY_SLOT, expectedPriceRouter); priceRouter = PriceRouter(expectedPriceRouter); uint256 assetsAfter = totalAssets(); if (checkTotalAssets) { if (assetsAfter < minAssets || assetsAfter > maxAssets) { revert Cellar__TotalAssetDeviatedOutsideRange(assetsAfter, minAssets, maxAssets); } } } // ========================================= POSITIONS CONFIG ========================================= /** * @notice Emitted when a position is added. * @param position id of position that was added * @param index index that position was added at */ event PositionAdded(uint32 position, uint256 index); /** * @notice Emitted when a position is removed. * @param position id of position that was removed * @param index index that position was removed from */ event PositionRemoved(uint32 position, uint256 index); /** * @notice Emitted when the positions at two indexes are swapped. * @param newPosition1 id of position (previously at index2) that replaced index1. * @param newPosition2 id of position (previously at index1) that replaced index2. * @param index1 index of first position involved in the swap * @param index2 index of second position involved in the swap. */ event PositionSwapped(uint32 newPosition1, uint32 newPosition2, uint256 index1, uint256 index2); /** * @notice Emitted when Governance adds/removes a position to/from the cellars catalogue. */ event PositionCatalogueAltered(uint32 positionId, bool inCatalogue); /** * @notice Emitted when Governance adds/removes an adaptor to/from the cellars catalogue. */ event AdaptorCatalogueAltered(address adaptor, bool inCatalogue); /** * @notice Attempted to add a position that is already being used. * @param position id of the position */ error Cellar__PositionAlreadyUsed(uint32 position); /** * @notice Attempted to make an unused position the holding position. * @param position id of the position */ error Cellar__PositionNotUsed(uint32 position); /** * @notice Attempted to add a position that is not in the catalogue. * @param position id of the position */ error Cellar__PositionNotInCatalogue(uint32 position); /** * @notice Attempted an action on a position that is required to be empty before the action can be performed. * @param position address of the non-empty position * @param sharesRemaining amount of shares remaining in the position */ error Cellar__PositionNotEmpty(uint32 position, uint256 sharesRemaining); /** * @notice Attempted an operation with an asset that was different then the one expected. * @param asset address of the asset * @param expectedAsset address of the expected asset */ error Cellar__AssetMismatch(address asset, address expectedAsset); /** * @notice Attempted to add a position when the position array is full. * @param maxPositions maximum number of positions that can be used */ error Cellar__PositionArrayFull(uint256 maxPositions); /** * @notice Attempted to add a position, with mismatched debt. * @param position the posiiton id that was mismatched */ error Cellar__DebtMismatch(uint32 position); /** * @notice Attempted to remove the Cellars holding position. */ error Cellar__RemovingHoldingPosition(); /** * @notice Attempted to add an invalid holding position. * @param positionId the id of the invalid position. */ error Cellar__InvalidHoldingPosition(uint32 positionId); /** * @notice Attempted to force out the wrong position. */ error Cellar__FailedToForceOutPosition(); /** * @notice Array of uint32s made up of cellars credit positions Ids. */ uint32[] internal creditPositions; /** * @notice Array of uint32s made up of cellars debt positions Ids. */ uint32[] internal debtPositions; /** * @notice Tell whether a position is currently used. */ mapping(uint256 => bool) public isPositionUsed; /** * @notice Get position data given position id. */ mapping(uint32 => Registry.PositionData) internal getPositionData; /** * @notice Get the ids of the credit positions currently used by the cellar. */ function getCreditPositions() external view returns (uint32[] memory) { return creditPositions; } /** * @notice Get the ids of the debt positions currently used by the cellar. */ function getDebtPositions() external view returns (uint32[] memory) { return debtPositions; } /** * @notice Maximum amount of positions a cellar can have in it's credit/debt arrays. */ uint256 internal constant MAX_POSITIONS = 32; /** * @notice Allows owner to change the holding position. * @dev Callable by Sommelier Strategist. */ function setHoldingPosition(uint32 positionId) public { _isAuthorized(); if (!isPositionUsed[positionId]) revert Cellar__PositionNotUsed(positionId); if (_assetOf(positionId) != asset) revert Cellar__AssetMismatch(address(asset), address(_assetOf(positionId))); if (getPositionData[positionId].isDebt) revert Cellar__InvalidHoldingPosition(positionId); holdingPosition = positionId; } /** * @notice Positions the strategist is approved to use without any governance intervention. */ mapping(uint32 => bool) internal positionCatalogue; /** * @notice Adaptors the strategist is approved to use without any governance intervention. */ mapping(address => bool) internal adaptorCatalogue; /** * @notice Allows Governance to add positions to this cellar's catalogue. * @dev Callable by Sommelier Governance. */ function addPositionToCatalogue(uint32 positionId) public { _isAuthorized(); // Make sure position is not paused and is trusted. registry.revertIfPositionIsNotTrusted(positionId); positionCatalogue[positionId] = true; emit PositionCatalogueAltered(positionId, true); } /** * @notice Allows Governance to remove positions from this cellar's catalogue. * @dev Callable by Sommelier Strategist. */ function removePositionFromCatalogue(uint32 positionId) external { _isAuthorized(); positionCatalogue[positionId] = false; emit PositionCatalogueAltered(positionId, false); } /** * @notice Allows Governance to add adaptors to this cellar's catalogue. * @dev Callable by Sommelier Governance. */ function addAdaptorToCatalogue(address adaptor) external { _isAuthorized(); // Make sure adaptor is trusted. registry.revertIfAdaptorIsNotTrusted(adaptor); adaptorCatalogue[adaptor] = true; emit AdaptorCatalogueAltered(adaptor, true); } /** * @notice Allows Governance to remove adaptors from this cellar's catalogue. * @dev Callable by Sommelier Strategist. */ function removeAdaptorFromCatalogue(address adaptor) external { _isAuthorized(); adaptorCatalogue[adaptor] = false; emit AdaptorCatalogueAltered(adaptor, false); } /** * @notice Insert a trusted position to the list of positions used by the cellar at a given index. * @param index index at which to insert the position * @param positionId id of position to add * @param configurationData data used to configure how the position behaves * @dev Callable by Sommelier Strategist. */ function addPosition(uint32 index, uint32 positionId, bytes memory configurationData, bool inDebtArray) public { _isAuthorized(); _whenNotShutdown(); // Check if position is already being used. if (isPositionUsed[positionId]) revert Cellar__PositionAlreadyUsed(positionId); // Check if position is in the position catalogue. if (!positionCatalogue[positionId]) revert Cellar__PositionNotInCatalogue(positionId); // Grab position data from registry. // Also checks if position is not trusted and reverts if so. (address adaptor, bool isDebt, bytes memory adaptorData) = registry.addPositionToCellar(positionId); if (isDebt != inDebtArray) revert Cellar__DebtMismatch(positionId); // Copy position data from registry to here. getPositionData[positionId] = Registry.PositionData({ adaptor: adaptor, isDebt: isDebt, adaptorData: adaptorData, configurationData: configurationData }); if (isDebt) { if (debtPositions.length >= MAX_POSITIONS) revert Cellar__PositionArrayFull(MAX_POSITIONS); // Add new position at a specified index. debtPositions.add(index, positionId); } else { if (creditPositions.length >= MAX_POSITIONS) revert Cellar__PositionArrayFull(MAX_POSITIONS); // Add new position at a specified index. creditPositions.add(index, positionId); } isPositionUsed[positionId] = true; emit PositionAdded(positionId, index); } /** * @notice Remove the position at a given index from the list of positions used by the cellar. * @dev Called by strategist. * @param index index at which to remove the position * @dev Callable by Sommelier Strategist. */ function removePosition(uint32 index, bool inDebtArray) external { _isAuthorized(); // Get position being removed. uint32 positionId = inDebtArray ? debtPositions[index] : creditPositions[index]; // Only remove position if it is empty, and if it is not the holding position. uint256 positionBalance = _balanceOf(positionId); if (positionBalance > 0) revert Cellar__PositionNotEmpty(positionId, positionBalance); _removePosition(index, positionId, inDebtArray); } /** * @notice Allows Sommelier Governance to forceably remove a position from the Cellar without checking its balance is zero. * @dev Callable by Sommelier Governance. */ function forcePositionOut(uint32 index, uint32 positionId, bool inDebtArray) external { _isAuthorized(); // Get position being removed. uint32 _positionId = inDebtArray ? debtPositions[index] : creditPositions[index]; // Make sure position id right, and is distrusted. if (positionId != _positionId || registry.isPositionTrusted(positionId)) { revert Cellar__FailedToForceOutPosition(); } _removePosition(index, positionId, inDebtArray); } /** * @notice Internal helper function to remove positions from cellars tracked arrays. */ function _removePosition(uint32 index, uint32 positionId, bool inDebtArray) internal { if (positionId == holdingPosition) revert Cellar__RemovingHoldingPosition(); if (inDebtArray) { // Remove position at the given index. debtPositions.remove(index); } else { creditPositions.remove(index); } isPositionUsed[positionId] = false; delete getPositionData[positionId]; emit PositionRemoved(positionId, index); } /** * @notice Swap the positions at two given indexes. * @param index1 index of first position to swap * @param index2 index of second position to swap * @param inDebtArray bool indicating to switch positions in the debt array, or the credit array. * @dev Callable by Sommelier Strategist. */ function swapPositions(uint32 index1, uint32 index2, bool inDebtArray) external { _isAuthorized(); // Get the new positions that will be at each index. uint32 newPosition1; uint32 newPosition2; if (inDebtArray) { newPosition1 = debtPositions[index2]; newPosition2 = debtPositions[index1]; // Swap positions. (debtPositions[index1], debtPositions[index2]) = (newPosition1, newPosition2); } else { newPosition1 = creditPositions[index2]; newPosition2 = creditPositions[index1]; // Swap positions. (creditPositions[index1], creditPositions[index2]) = (newPosition1, newPosition2); } emit PositionSwapped(newPosition1, newPosition2, index1, index2); } // =============================================== FEES CONFIG =============================================== /** * @notice Emitted when strategist platform fee cut is changed. * @param oldPlatformCut value strategist platform fee cut was changed from * @param newPlatformCut value strategist platform fee cut was changed to */ event StrategistPlatformCutChanged(uint64 oldPlatformCut, uint64 newPlatformCut); /** * @notice Emitted when strategists payout address is changed. * @param oldPayoutAddress value strategists payout address was changed from * @param newPayoutAddress value strategists payout address was changed to */ event StrategistPayoutAddressChanged(address oldPayoutAddress, address newPayoutAddress); /** * @notice Attempted to change strategist fee cut with invalid value. */ error Cellar__InvalidFeeCut(); /** * @notice Attempted to change platform fee with invalid value. */ error Cellar__InvalidFee(); /** * @notice Data related to fees. * @param strategistPlatformCut Determines how much platform fees go to strategist. * This should be a value out of 1e18 (ie. 1e18 represents 100%, 0 represents 0%). * @param platformFee The percentage of total assets accrued as platform fees over a year. * This should be a value out of 1e18 (ie. 1e18 represents 100%, 0 represents 0%). * @param strategistPayoutAddress Address to send the strategists fee shares. */ struct FeeData { uint64 strategistPlatformCut; uint64 platformFee; uint64 lastAccrual; address strategistPayoutAddress; } /** * @notice Stores all fee data for cellar. */ FeeData public feeData = FeeData({ strategistPlatformCut: 0.75e18, platformFee: 0.01e18, lastAccrual: 0, strategistPayoutAddress: address(0) }); /** * @notice Sets the max possible performance fee for this cellar. */ uint64 internal constant MAX_PLATFORM_FEE = 0.2e18; /** * @notice Sets the max possible fee cut for this cellar. */ uint64 internal constant MAX_FEE_CUT = 1e18; /** * @notice Sets the Strategists cut of platform fees * @param cut the platform cut for the strategist * @dev Callable by Sommelier Governance. */ function setStrategistPlatformCut(uint64 cut) external { _isAuthorized(); if (cut > MAX_FEE_CUT) revert Cellar__InvalidFeeCut(); emit StrategistPlatformCutChanged(feeData.strategistPlatformCut, cut); feeData.strategistPlatformCut = cut; } /** * @notice Sets the Strategists payout address * @param payout the new strategist payout address * @dev Callable by Sommelier Strategist. */ function setStrategistPayoutAddress(address payout) external { _isAuthorized(); emit StrategistPayoutAddressChanged(feeData.strategistPayoutAddress, payout); feeData.strategistPayoutAddress = payout; } // =========================================== EMERGENCY LOGIC =========================================== /** * @notice Emitted when cellar emergency state is changed. * @param isShutdown whether the cellar is shutdown */ event ShutdownChanged(bool isShutdown); /** * @notice Attempted action was prevented due to contract being shutdown. */ error Cellar__ContractShutdown(); /** * @notice Attempted action was prevented due to contract not being shutdown. */ error Cellar__ContractNotShutdown(); /** * @notice Attempted to interact with the cellar when it is paused. */ error Cellar__Paused(); /** * @notice View function external contracts can use to see if the cellar is paused. */ function isPaused() external view returns (bool) { if (!ignorePause) { return registry.isCallerPaused(address(this)); } return false; } /** * @notice Pauses all user entry/exits, and strategist rebalances. */ function _checkIfPaused() internal view { if (!ignorePause) { if (registry.isCallerPaused(address(this))) revert Cellar__Paused(); } } /** * @notice Allows governance to choose whether or not to respect a pause. * @dev Callable by Sommelier Governance. */ function toggleIgnorePause() external { _isAuthorized(); ignorePause = ignorePause ? false : true; } /** * @notice Prevent a function from being called during a shutdown. */ function _whenNotShutdown() internal view { if (isShutdown) revert Cellar__ContractShutdown(); } /** * @notice Shutdown the cellar. Used in an emergency or if the cellar has been deprecated. * @dev Callable by Sommelier Strategist. */ function initiateShutdown() external { _isAuthorized(); _whenNotShutdown(); isShutdown = true; emit ShutdownChanged(true); } /** * @notice Restart the cellar. * @dev Callable by Sommelier Strategist. */ function liftShutdown() external { _isAuthorized(); if (!isShutdown) revert Cellar__ContractNotShutdown(); isShutdown = false; emit ShutdownChanged(false); } // =========================================== CONSTRUCTOR =========================================== /** * @notice Id to get the gravity bridge from the registry. */ uint256 internal constant GRAVITY_BRIDGE_REGISTRY_SLOT = 0; /** * @notice Id to get the price router from the registry. */ uint256 internal constant PRICE_ROUTER_REGISTRY_SLOT = 2; /** * @notice The minimum amount of shares to be minted in the contructor. */ uint256 internal constant MINIMUM_CONSTRUCTOR_MINT = 1e4; /** * @notice Attempted to deploy contract without minting enough shares. */ error Cellar__MinimumConstructorMintNotMet(); /** * @notice Address of the platform's registry contract. Used to get the latest address of modules. */ Registry public immutable registry; /** * @dev Owner should be set to the Gravity Bridge, which relays instructions from the Steward * module to the cellars. * https://github.com/PeggyJV/steward * https://github.com/cosmos/gravity-bridge/blob/main/solidity/contracts/Gravity.sol * @param _registry address of the platform's registry contract * @param _asset address of underlying token used for the for accounting, depositing, and withdrawing * @param _name name of this cellar's share token * @param _symbol symbol of this cellar's share token * @param _holdingPosition the holding position of the Cellar * must use a position that does NOT call back to cellar on use(Like ERC20 positions). * @param _holdingPositionConfig configuration data for holding position * @param _initialDeposit initial amount of assets to deposit into the Cellar * @param _strategistPlatformCut platform cut to use * @param _shareSupplyCap starting share supply cap */ constructor( address _owner, Registry _registry, ERC20 _asset, string memory _name, string memory _symbol, uint32 _holdingPosition, bytes memory _holdingPositionConfig, uint256 _initialDeposit, uint64 _strategistPlatformCut, uint192 _shareSupplyCap ) ERC4626(_asset, _name, _symbol) Auth(msg.sender, Authority(address(0))) { registry = _registry; priceRouter = PriceRouter(_registry.getAddress(PRICE_ROUTER_REGISTRY_SLOT)); // Initialize holding position. addPositionToCatalogue(_holdingPosition); addPosition(0, _holdingPosition, _holdingPositionConfig, false); setHoldingPosition(_holdingPosition); // Update Share Supply Cap. shareSupplyCap = _shareSupplyCap; if (_initialDeposit < MINIMUM_CONSTRUCTOR_MINT) revert Cellar__MinimumConstructorMintNotMet(); // Deposit into Cellar, and mint shares to Deployer address. _asset.safeTransferFrom(_owner, address(this), _initialDeposit); // Set the share price as 1:1 with underlying asset. _mint(msg.sender, _initialDeposit); // Deposit _initialDeposit into holding position. _depositTo(_holdingPosition, _initialDeposit); feeData.strategistPlatformCut = _strategistPlatformCut; transferOwnership(_owner); } // =========================================== CORE LOGIC =========================================== /** * @notice Attempted an action with zero shares. */ error Cellar__ZeroShares(); /** * @notice Attempted an action with zero assets. */ error Cellar__ZeroAssets(); /** * @notice Withdraw did not withdraw all assets. * @param assetsOwed the remaining assets owed that were not withdrawn. */ error Cellar__IncompleteWithdraw(uint256 assetsOwed); /** * @notice Attempted to withdraw an illiquid position. * @param illiquidPosition the illiquid position. */ error Cellar__IlliquidWithdraw(address illiquidPosition); /** * @notice called at the beginning of deposit. */ function beforeDeposit(ERC20, uint256, uint256, address) internal view virtual { _whenNotShutdown(); _checkIfPaused(); } /** * @notice called at the end of deposit. * @param position the position to deposit to. * @param assets amount of assets deposited by user. */ function afterDeposit(uint32 position, uint256 assets, uint256, address) internal virtual { _depositTo(position, assets); } /** * @notice called at the beginning of withdraw. */ function beforeWithdraw(uint256, uint256, address, address) internal view virtual { _checkIfPaused(); } /** * @notice Called when users enter the cellar via deposit or mint. */ function _enter(ERC20 depositAsset, uint32 position, uint256 assets, uint256 shares, address receiver) internal virtual { beforeDeposit(asset, assets, shares, receiver); // Need to transfer before minting or ERC777s could reenter. depositAsset.safeTransferFrom(msg.sender, address(this), assets); _mint(receiver, shares); emit Deposit(msg.sender, receiver, assets, shares); afterDeposit(position, assets, shares, receiver); } /** * @notice Deposits assets into the cellar, and returns shares to receiver. * @param assets amount of assets deposited by user. * @param receiver address to receive the shares. * @return shares amount of shares given for deposit. */ function deposit(uint256 assets, address receiver) public virtual override nonReentrant returns (uint256 shares) { // Use `_calculateTotalAssetsOrTotalAssetsWithdrawable` instead of totalAssets bc re-entrancy is already checked in this function. (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true); // Check for rounding error since we round down in previewDeposit. if ((shares = _convertToShares(assets, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroShares(); if ((_totalSupply + shares) > shareSupplyCap) revert Cellar__ShareSupplyCapExceeded(); _enter(asset, holdingPosition, assets, shares, receiver); } /** * @notice Mints shares from the cellar, and returns shares to receiver. * @param shares amount of shares requested by user. * @param receiver address to receive the shares. * @return assets amount of assets deposited into the cellar. */ function mint(uint256 shares, address receiver) public override nonReentrant returns (uint256 assets) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true); // previewMint rounds up, but initial mint could return zero assets, so check for rounding error. if ((assets = _previewMint(shares, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroAssets(); if ((_totalSupply + shares) > shareSupplyCap) revert Cellar__ShareSupplyCapExceeded(); _enter(asset, holdingPosition, assets, shares, receiver); } /** * @notice Called when users exit the cellar via withdraw or redeem. */ function _exit(uint256 assets, uint256 shares, address receiver, address owner) internal { beforeWithdraw(assets, shares, receiver, owner); if (msg.sender != owner) { uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } _burn(owner, shares); emit Withdraw(msg.sender, receiver, owner, assets, shares); _withdrawInOrder(assets, receiver); /// @notice `afterWithdraw` is currently not used. // afterWithdraw(assets, shares, receiver, owner); } /** * @notice Withdraw assets from the cellar by redeeming shares. * @dev Unlike conventional ERC4626 contracts, this may not always return one asset to the receiver. * Since there are no swaps involved in this function, the receiver may receive multiple * assets. The value of all the assets returned will be equal to the amount defined by * `assets` denominated in the `asset` of the cellar (eg. if `asset` is USDC and `assets` * is 1000, then the receiver will receive $1000 worth of assets in either one or many * tokens). * @param assets equivalent value of the assets withdrawn, denominated in the cellar's asset * @param receiver address that will receive withdrawn assets * @param owner address that owns the shares being redeemed * @return shares amount of shares redeemed */ function withdraw(uint256 assets, address receiver, address owner) public override nonReentrant returns (uint256 shares) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false); // No need to check for rounding error, `previewWithdraw` rounds up. shares = _previewWithdraw(assets, _totalAssets, _totalSupply); _exit(assets, shares, receiver, owner); } /** * @notice Redeem shares to withdraw assets from the cellar. * @dev Unlike conventional ERC4626 contracts, this may not always return one asset to the receiver. * Since there are no swaps involved in this function, the receiver may receive multiple * assets. The value of all the assets returned will be equal to the amount defined by * `assets` denominated in the `asset` of the cellar (eg. if `asset` is USDC and `assets` * is 1000, then the receiver will receive $1000 worth of assets in either one or many * tokens). * @param shares amount of shares to redeem * @param receiver address that will receive withdrawn assets * @param owner address that owns the shares being redeemed * @return assets equivalent value of the assets withdrawn, denominated in the cellar's asset */ function redeem(uint256 shares, address receiver, address owner) public override nonReentrant returns (uint256 assets) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false); // Check for rounding error since we round down in previewRedeem. if ((assets = _convertToAssets(shares, _totalAssets, _totalSupply)) == 0) revert Cellar__ZeroAssets(); _exit(assets, shares, receiver, owner); } /** * @notice Struct used in `_withdrawInOrder` in order to hold multiple pricing values in a single variable. * @dev Prevents stack too deep errors. */ struct WithdrawPricing { uint256 priceBaseUSD; uint256 oneBase; uint256 priceQuoteUSD; uint256 oneQuote; } /** * @notice Multipler used to insure calculations use very high precision. */ uint256 private constant PRECISION_MULTIPLIER = 1e18; /** * @dev Withdraw from positions in the order defined by `positions`. * @param assets the amount of assets to withdraw from cellar * @param receiver the address to sent withdrawn assets to * @dev Only loop through credit array because debt can not be withdraw by users. */ function _withdrawInOrder(uint256 assets, address receiver) internal { // Save asset price in USD, and decimals to reduce external calls. WithdrawPricing memory pricingInfo; pricingInfo.priceQuoteUSD = priceRouter.getPriceInUSD(asset); pricingInfo.oneQuote = 10 ** decimals; uint256 creditLength = creditPositions.length; for (uint256 i; i < creditLength; ++i) { uint32 position = creditPositions[i]; uint256 withdrawableBalance = _withdrawableFrom(position); // Move on to next position if this one is empty. if (withdrawableBalance == 0) continue; ERC20 positionAsset = _assetOf(position); pricingInfo.priceBaseUSD = priceRouter.getPriceInUSD(positionAsset); pricingInfo.oneBase = 10 ** positionAsset.decimals(); uint256 totalWithdrawableBalanceInAssets; { uint256 withdrawableBalanceInUSD = (PRECISION_MULTIPLIER * withdrawableBalance).mulDivDown( pricingInfo.priceBaseUSD, pricingInfo.oneBase ); totalWithdrawableBalanceInAssets = withdrawableBalanceInUSD.mulDivDown(pricingInfo.oneQuote, pricingInfo.priceQuoteUSD); totalWithdrawableBalanceInAssets = totalWithdrawableBalanceInAssets / PRECISION_MULTIPLIER; } // We want to pull as much as we can from this position, but no more than needed. uint256 amount; if (totalWithdrawableBalanceInAssets > assets) { // Convert assets into position asset. uint256 assetsInUSD = (PRECISION_MULTIPLIER * assets).mulDivDown(pricingInfo.priceQuoteUSD, pricingInfo.oneQuote); amount = assetsInUSD.mulDivDown(pricingInfo.oneBase, pricingInfo.priceBaseUSD); amount = amount / PRECISION_MULTIPLIER; assets = 0; } else { amount = withdrawableBalance; assets = assets - totalWithdrawableBalanceInAssets; } // Withdraw from position. _withdrawFrom(position, amount, receiver); // Stop if no more assets to withdraw. if (assets == 0) break; } // If withdraw did not remove all assets owed, revert. if (assets > 0) revert Cellar__IncompleteWithdraw(assets); } // ========================================= ACCOUNTING LOGIC ========================================= /** * @notice Get the Cellars Total Assets, and Total Supply. * @dev bool input is not used, but if it were used the following is true. * true: return the largest possible total assets * false: return the smallest possible total assets */ function _getTotalAssetsAndTotalSupply(bool) internal view virtual returns (uint256 _totalAssets, uint256 _totalSupply) { _totalAssets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false); _totalSupply = totalSupply; } /** * @notice Internal accounting function that can report total assets, or total assets withdrawable. * @param reportWithdrawable if true, then the withdrawable total assets is reported, * if false, then the total assets is reported */ function _calculateTotalAssetsOrTotalAssetsWithdrawable(bool reportWithdrawable) internal view returns (uint256 assets) { uint256 numOfCreditPositions = creditPositions.length; ERC20[] memory creditAssets = new ERC20[](numOfCreditPositions); uint256[] memory creditBalances = new uint256[](numOfCreditPositions); // If we just need the withdrawable, then query credit array value. if (reportWithdrawable) { for (uint256 i; i < numOfCreditPositions; ++i) { uint32 position = creditPositions[i]; // If the withdrawable balance is zero there is no point to query the asset since a zero balance has zero value. if ((creditBalances[i] = _withdrawableFrom(position)) == 0) continue; creditAssets[i] = _assetOf(position); } assets = priceRouter.getValues(creditAssets, creditBalances, asset); } else { uint256 numOfDebtPositions = debtPositions.length; ERC20[] memory debtAssets = new ERC20[](numOfDebtPositions); uint256[] memory debtBalances = new uint256[](numOfDebtPositions); for (uint256 i; i < numOfCreditPositions; ++i) { uint32 position = creditPositions[i]; // If the balance is zero there is no point to query the asset since a zero balance has zero value. if ((creditBalances[i] = _balanceOf(position)) == 0) continue; creditAssets[i] = _assetOf(position); } for (uint256 i; i < numOfDebtPositions; ++i) { uint32 position = debtPositions[i]; // If the balance is zero there is no point to query the asset since a zero balance has zero value. if ((debtBalances[i] = _balanceOf(position)) == 0) continue; debtAssets[i] = _assetOf(position); } assets = priceRouter.getValuesDelta(creditAssets, creditBalances, debtAssets, debtBalances, asset); } } /** * @notice The total amount of assets in the cellar. * @dev EIP4626 states totalAssets needs to be inclusive of fees. * Since performance fees mint shares, total assets remains unchanged, * so this implementation is inclusive of fees even though it does not explicitly show it. * @dev EIP4626 states totalAssets must not revert, but it is possible for `totalAssets` to revert * so it does NOT conform to ERC4626 standards. * @dev Run a re-entrancy check because totalAssets can be wrong if re-entering from deposit/withdraws. */ function totalAssets() public view override returns (uint256 assets) { _checkIfPaused(); require(!locked, "REENTRANCY"); assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false); } /** * @notice The total amount of withdrawable assets in the cellar. * @dev Run a re-entrancy check because totalAssetsWithdrawable can be wrong if re-entering from deposit/withdraws. */ function totalAssetsWithdrawable() public view returns (uint256 assets) { _checkIfPaused(); require(!locked, "REENTRANCY"); assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(true); } /** * @notice The amount of assets that the cellar would exchange for the amount of shares provided. * @dev Use preview functions to get accurate assets. * @dev Under estimates assets. * @param shares amount of shares to convert * @return assets the shares can be exchanged for */ function convertToAssets(uint256 shares) public view override returns (uint256 assets) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false); assets = _convertToAssets(shares, _totalAssets, _totalSupply); } /** * @notice The amount of shares that the cellar would exchange for the amount of assets provided. * @dev Use preview functions to get accurate shares. * @dev Under estimates shares. * @param assets amount of assets to convert * @return shares the assets can be exchanged for */ function convertToShares(uint256 assets) public view override returns (uint256 shares) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true); shares = _convertToShares(assets, _totalAssets, _totalSupply); } /** * @notice Simulate the effects of minting shares at the current block, given current on-chain conditions. * @param shares amount of shares to mint * @return assets that will be deposited */ function previewMint(uint256 shares) public view override returns (uint256 assets) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true); assets = _previewMint(shares, _totalAssets, _totalSupply); } /** * @notice Simulate the effects of withdrawing assets at the current block, given current on-chain conditions. * @param assets amount of assets to withdraw * @return shares that will be redeemed */ function previewWithdraw(uint256 assets) public view override returns (uint256 shares) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false); shares = _previewWithdraw(assets, _totalAssets, _totalSupply); } /** * @notice Simulate the effects of depositing assets at the current block, given current on-chain conditions. * @param assets amount of assets to deposit * @return shares that will be minted */ function previewDeposit(uint256 assets) public view override returns (uint256 shares) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true); shares = _convertToShares(assets, _totalAssets, _totalSupply); } /** * @notice Simulate the effects of redeeming shares at the current block, given current on-chain conditions. * @param shares amount of shares to redeem * @return assets that will be returned */ function previewRedeem(uint256 shares) public view override returns (uint256 assets) { (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false); assets = _convertToAssets(shares, _totalAssets, _totalSupply); } /** * @notice Finds the max amount of value an `owner` can remove from the cellar. * @param owner address of the user to find max value. * @param inShares if false, then returns value in terms of assets * if true then returns value in terms of shares */ function _findMax(address owner, bool inShares) internal view virtual returns (uint256 maxOut) { _checkIfPaused(); // Get amount of assets to withdraw. (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(false); uint256 assets = _convertToAssets(balanceOf[owner], _totalAssets, _totalSupply); uint256 withdrawable = _calculateTotalAssetsOrTotalAssetsWithdrawable(true); maxOut = assets <= withdrawable ? assets : withdrawable; if (inShares) maxOut = _convertToShares(maxOut, _totalAssets, _totalSupply); // else leave maxOut in terms of assets. } /** * @notice Returns the max amount withdrawable by a user inclusive of performance fees * @dev EIP4626 states maxWithdraw must not revert, but it is possible for `totalAssets` to revert * so it does NOT conform to ERC4626 standards. * @param owner address to check maxWithdraw of. * @return the max amount of assets withdrawable by `owner`. */ function maxWithdraw(address owner) public view override returns (uint256) { require(!locked, "REENTRANCY"); return _findMax(owner, false); } /** * @notice Returns the max amount shares redeemable by a user * @dev EIP4626 states maxRedeem must not revert, but it is possible for `totalAssets` to revert * so it does NOT conform to ERC4626 standards. * @param owner address to check maxRedeem of. * @return the max amount of shares redeemable by `owner`. */ function maxRedeem(address owner) public view override returns (uint256) { require(!locked, "REENTRANCY"); return _findMax(owner, true); } /** * @dev Used to more efficiently convert amount of shares to assets using a stored `totalAssets` value. */ function _convertToAssets(uint256 shares, uint256 _totalAssets, uint256 _totalSupply) internal pure returns (uint256 assets) { assets = shares.mulDivDown(_totalAssets, _totalSupply); } /** * @dev Used to more efficiently convert amount of assets to shares using a stored `totalAssets` value. */ function _convertToShares(uint256 assets, uint256 _totalAssets, uint256 _totalSupply) internal pure returns (uint256 shares) { shares = assets.mulDivDown(_totalSupply, _totalAssets); } /** * @dev Used to more efficiently simulate minting shares using a stored `totalAssets` value. */ function _previewMint(uint256 shares, uint256 _totalAssets, uint256 _totalSupply) internal pure returns (uint256 assets) { assets = shares.mulDivUp(_totalAssets, _totalSupply); } /** * @dev Used to more efficiently simulate withdrawing assets using a stored `totalAssets` value. */ function _previewWithdraw(uint256 assets, uint256 _totalAssets, uint256 _totalSupply) internal pure returns (uint256 shares) { shares = assets.mulDivUp(_totalSupply, _totalAssets); } // =========================================== ADAPTOR LOGIC =========================================== /** * @notice Emitted on when the rebalance deviation is changed. * @param oldDeviation the old rebalance deviation * @param newDeviation the new rebalance deviation */ event RebalanceDeviationChanged(uint256 oldDeviation, uint256 newDeviation); /** * @notice totalAssets deviated outside the range set by `allowedRebalanceDeviation`. * @param assets the total assets in the cellar * @param min the minimum allowed assets * @param max the maximum allowed assets */ error Cellar__TotalAssetDeviatedOutsideRange(uint256 assets, uint256 min, uint256 max); /** * @notice Total shares in a cellar changed when they should stay constant. * @param current the current amount of total shares * @param expected the expected amount of total shares */ error Cellar__TotalSharesMustRemainConstant(uint256 current, uint256 expected); /** * @notice Total shares in a cellar changed when they should stay constant. * @param requested the requested rebalance deviation * @param max the max rebalance deviation. */ error Cellar__InvalidRebalanceDeviation(uint256 requested, uint256 max); /** * @notice Strategist attempted to use an adaptor that is either paused or is not trusted by governance. * @param adaptor the adaptor address that is paused or not trusted. */ error Cellar__CallToAdaptorNotAllowed(address adaptor); /** * @notice Stores the max possible rebalance deviation for this cellar. */ uint64 internal constant MAX_REBALANCE_DEVIATION = 0.1e18; /** * @notice The percent the total assets of a cellar may deviate during a `callOnAdaptor`(rebalance) call. */ uint256 internal allowedRebalanceDeviation = 0.0003e18; /** * @notice Allows governance to change this cellars rebalance deviation. * @param newDeviation the new rebalance deviation value. * @dev Callable by Sommelier Governance. */ function setRebalanceDeviation(uint256 newDeviation) external { _isAuthorized(); if (newDeviation > MAX_REBALANCE_DEVIATION) { revert Cellar__InvalidRebalanceDeviation(newDeviation, MAX_REBALANCE_DEVIATION); } uint256 oldDeviation = allowedRebalanceDeviation; allowedRebalanceDeviation = newDeviation; emit RebalanceDeviationChanged(oldDeviation, newDeviation); } /** * @notice Struct used to make calls to adaptors. * @param adaptor the address of the adaptor to make calls to * @param the abi encoded function calls to make to the `adaptor` */ struct AdaptorCall { address adaptor; bytes[] callData; } /** * @notice Emitted when adaptor calls are made. */ event AdaptorCalled(address adaptor, bytes data); /** * @notice Internal helper function that accepts an Adaptor Call array, and makes calls to each adaptor. */ function _makeAdaptorCalls(AdaptorCall[] memory data) internal { for (uint256 i = 0; i < data.length; ++i) { address adaptor = data[i].adaptor; // Revert if adaptor not in catalogue, or adaptor is paused. if (!adaptorCatalogue[adaptor]) revert Cellar__CallToAdaptorNotAllowed(adaptor); for (uint256 j = 0; j < data[i].callData.length; j++) { adaptor.functionDelegateCall(data[i].callData[j]); emit AdaptorCalled(adaptor, data[i].callData[j]); } } } /** * @notice Allows strategists to manage their Cellar using arbitrary logic calls to adaptors. * @dev There are several safety checks in this function to prevent strategists from abusing it. * - `blockExternalReceiver` * - `totalAssets` must not change by much * - `totalShares` must remain constant * - adaptors must be set up to be used with this cellar * @dev Since `totalAssets` is allowed to deviate slightly, strategists could abuse this by sending * multiple `callOnAdaptor` calls rapidly, to gradually change the share price. * To mitigate this, rate limiting will be put in place on the Sommelier side. * @dev Callable by Sommelier Strategist, and Automation Actions contract. */ function callOnAdaptor(AdaptorCall[] calldata data) external virtual nonReentrant { _isAuthorized(); _whenNotShutdown(); _checkIfPaused(); blockExternalReceiver = true; // Record `totalAssets` and `totalShares` before making any external calls. uint256 minimumAllowedAssets; uint256 maximumAllowedAssets; uint256 totalShares; { uint256 assetsBeforeAdaptorCall = _calculateTotalAssetsOrTotalAssetsWithdrawable(false); minimumAllowedAssets = assetsBeforeAdaptorCall.mulDivUp((1e18 - allowedRebalanceDeviation), 1e18); maximumAllowedAssets = assetsBeforeAdaptorCall.mulDivUp((1e18 + allowedRebalanceDeviation), 1e18); totalShares = totalSupply; } // Run all adaptor calls. _makeAdaptorCalls(data); // After making every external call, check that the totalAssets has not deviated significantly, and that totalShares is the same. uint256 assets = _calculateTotalAssetsOrTotalAssetsWithdrawable(false); if (assets < minimumAllowedAssets || assets > maximumAllowedAssets) { revert Cellar__TotalAssetDeviatedOutsideRange(assets, minimumAllowedAssets, maximumAllowedAssets); } if (totalShares != totalSupply) revert Cellar__TotalSharesMustRemainConstant(totalSupply, totalShares); blockExternalReceiver = false; } // ============================================ LIMITS LOGIC ============================================ /** * @notice Attempted entry would raise totalSupply above Share Supply Cap. */ error Cellar__ShareSupplyCapExceeded(); /** * @notice Proposed share supply cap is not logical. */ error Cellar__InvalidShareSupplyCap(); /** * @notice Increases the share supply cap. * @dev Callable by Sommelier Governance. */ function increaseShareSupplyCap(uint192 _newShareSupplyCap) public { _isAuthorized(); if (_newShareSupplyCap < shareSupplyCap) revert Cellar__InvalidShareSupplyCap(); shareSupplyCap = _newShareSupplyCap; } /** * @notice Decreases the share supply cap. * @dev Callable by Sommelier Strategist. */ function decreaseShareSupplyCap(uint192 _newShareSupplyCap) public { _isAuthorized(); if (_newShareSupplyCap > shareSupplyCap) revert Cellar__InvalidShareSupplyCap(); shareSupplyCap = _newShareSupplyCap; } /** * @notice Total amount of assets that can be deposited for a user. * @return assets maximum amount of assets that can be deposited */ function maxDeposit(address) public view override returns (uint256) { if (isShutdown) return 0; uint192 _cap = shareSupplyCap; if ((_cap = shareSupplyCap) == type(uint192).max) return type(uint256).max; (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true); if (_totalSupply >= _cap) { return 0; } else { uint256 shareDelta = _cap - _totalSupply; return _convertToAssets(shareDelta, _totalAssets, _totalSupply); } } /** * @notice Total amount of shares that can be minted for a user. * @return shares maximum amount of shares that can be minted */ function maxMint(address) public view override returns (uint256) { if (isShutdown) return 0; uint192 _cap; if ((_cap = shareSupplyCap) == type(uint192).max) return type(uint256).max; uint256 _totalSupply = totalSupply; return _totalSupply >= _cap ? 0 : _cap - _totalSupply; } // ========================================== HELPER FUNCTIONS ========================================== /** * @dev Deposit into a position according to its position type and update related state. * @param position address to deposit funds into * @param assets the amount of assets to deposit into the position */ function _depositTo(uint32 position, uint256 assets) internal { address adaptor = getPositionData[position].adaptor; adaptor.functionDelegateCall( abi.encodeWithSelector( BaseAdaptor.deposit.selector, assets, getPositionData[position].adaptorData, getPositionData[position].configurationData ) ); } /** * @dev Withdraw from a position according to its position type and update related state. * @param position address to withdraw funds from * @param assets the amount of assets to withdraw from the position * @param receiver the address to sent withdrawn assets to */ function _withdrawFrom(uint32 position, uint256 assets, address receiver) internal { address adaptor = getPositionData[position].adaptor; adaptor.functionDelegateCall( abi.encodeWithSelector( BaseAdaptor.withdraw.selector, assets, receiver, getPositionData[position].adaptorData, getPositionData[position].configurationData ) ); } /** * @dev Get the withdrawable balance of a position according to its position type. * @param position position to get the withdrawable balance of */ function _withdrawableFrom(uint32 position) internal view returns (uint256) { // Debt positions always return 0 for their withdrawable. if (getPositionData[position].isDebt) return 0; return BaseAdaptor(getPositionData[position].adaptor).withdrawableFrom( getPositionData[position].adaptorData, getPositionData[position].configurationData ); } /** * @dev Get the balance of a position according to its position type. * @dev For ERC4626 position balances, this uses `previewRedeem` as opposed * to `convertToAssets` so that balanceOf ERC4626 positions includes fees taken on withdraw. * @param position position to get the balance of */ function _balanceOf(uint32 position) internal view returns (uint256) { address adaptor = getPositionData[position].adaptor; return BaseAdaptor(adaptor).balanceOf(getPositionData[position].adaptorData); } /** * @dev Get the asset of a position according to its position type. * @param position to get the asset of */ function _assetOf(uint32 position) internal view returns (ERC20) { address adaptor = getPositionData[position].adaptor; return BaseAdaptor(adaptor).assetOf(getPositionData[position].adaptorData); } /** * @notice Attempted to use an address from the registry, but address was not expected. */ error Cellar__ExpectedAddressDoesNotMatchActual(); /** * @notice Attempted to set an address to registry Id 0. */ error Cellar__SettingValueToRegistryIdZeroIsProhibited(); /** * @notice Verify that `_registryId` in registry corresponds to expected address. */ function _checkRegistryAddressAgainstExpected(uint256 _registryId, address _expected) internal view { if (_registryId == 0) revert Cellar__SettingValueToRegistryIdZeroIsProhibited(); if (registry.getAddress(_registryId) != _expected) revert Cellar__ExpectedAddressDoesNotMatchActual(); } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import { Registry, ERC20, Math, SafeTransferLib, Address } from "src/base/Cellar.sol"; import { CellarWithOracleWithBalancerFlashLoans } from "src/base/permutations/CellarWithOracleWithBalancerFlashLoans.sol"; contract CellarWithOracleWithBalancerFlashLoansWithMultiAssetDeposit is CellarWithOracleWithBalancerFlashLoans { using Math for uint256; using SafeTransferLib for ERC20; using Address for address; // ========================================= STRUCTS ========================================= /** * @notice Stores data needed for multi-asset deposits into this cellar. * @param isSupported bool indicating that mapped asset is supported * @param holdingPosition the holding position to deposit alternative assets into * @param depositFee fee taken for depositing this alternative asset */ struct AlternativeAssetData { bool isSupported; uint32 holdingPosition; uint32 depositFee; } // ========================================= CONSTANTS ========================================= /** * @notice The max possible fee that can be charged for an alternative asset deposit. */ uint32 internal constant MAX_ALTERNATIVE_ASSET_FEE = 0.1e8; // ========================================= GLOBAL STATE ========================================= /** * @notice Maps alternative assets to alternative asset data. */ mapping(ERC20 => AlternativeAssetData) public alternativeAssetData; //============================== ERRORS =============================== error CellarWithMultiAssetDeposit__AlternativeAssetFeeTooLarge(); error CellarWithMultiAssetDeposit__AlternativeAssetNotSupported(); error CellarWithMultiAssetDeposit__CallDataLengthNotSupported(); //============================== EVENTS =============================== /** * @notice Emitted when an alternative asset is added or updated. */ event AlternativeAssetUpdated(address asset, uint32 holdingPosition, uint32 depositFee); /** * @notice Emitted when an alternative asser is removed. */ event AlternativeAssetDropped(address asset); /** * @notice Emitted during multi asset deposits. * @dev Multi asset deposits will emit 2 events, the ERC4626 compliant Deposit event * and this event. These events were intentionally separated out so we can * keep the compliant event, but also have an event that emits the depositAsset. */ event MultiAssetDeposit( address indexed caller, address indexed owner, address depositAsset, uint256 assets, uint256 shares ); //============================== IMMUTABLES =============================== constructor( address _owner, Registry _registry, ERC20 _asset, string memory _name, string memory _symbol, uint32 _holdingPosition, bytes memory _holdingPositionConfig, uint256 _initialDeposit, uint64 _strategistPlatformCut, uint192 _shareSupplyCap, address _balancerVault ) CellarWithOracleWithBalancerFlashLoans( _owner, _registry, _asset, _name, _symbol, _holdingPosition, _holdingPositionConfig, _initialDeposit, _strategistPlatformCut, _shareSupplyCap, _balancerVault ) {} //============================== OWNER FUNCTIONS =============================== /** * @notice Allows the owner to add, or update an existing alternative asset deposit. * @dev Callable by Sommelier Strategists. * @param _alternativeAsset the ERC20 alternative asset that can be deposited * @param _alternativeHoldingPosition the holding position to direct alternative asset deposits to * @param _alternativeAssetFee the fee to charge for depositing this alternative asset */ function setAlternativeAssetData( ERC20 _alternativeAsset, uint32 _alternativeHoldingPosition, uint32 _alternativeAssetFee ) external { _isAuthorized(); if (!isPositionUsed[_alternativeHoldingPosition]) revert Cellar__PositionNotUsed(_alternativeHoldingPosition); if (_assetOf(_alternativeHoldingPosition) != _alternativeAsset) revert Cellar__AssetMismatch(address(_alternativeAsset), address(_assetOf(_alternativeHoldingPosition))); if (getPositionData[_alternativeHoldingPosition].isDebt) revert Cellar__InvalidHoldingPosition(_alternativeHoldingPosition); if (_alternativeAssetFee > MAX_ALTERNATIVE_ASSET_FEE) revert CellarWithMultiAssetDeposit__AlternativeAssetFeeTooLarge(); alternativeAssetData[_alternativeAsset] = AlternativeAssetData( true, _alternativeHoldingPosition, _alternativeAssetFee ); emit AlternativeAssetUpdated(address(_alternativeAsset), _alternativeHoldingPosition, _alternativeAssetFee); } /** * @notice Allows the owner to stop an alternative asset from being deposited. * @dev Callable by Sommelier Strategists. * @param _alternativeAsset the asset to not allow for alternative asset deposits anymore */ function dropAlternativeAssetData(ERC20 _alternativeAsset) external { _isAuthorized(); delete alternativeAssetData[_alternativeAsset]; emit AlternativeAssetDropped(address(_alternativeAsset)); } /** * @notice Deposits assets into the cellar, and returns shares to receiver. * @param assets amount of assets deposited by user. * @param receiver address to receive the shares. * @return shares amount of shares given for deposit. */ function deposit(uint256 assets, address receiver) public override nonReentrant returns (uint256 shares) { shares = _deposit(asset, assets, assets, assets, holdingPosition, receiver); } /** * @notice Allows users to deposit into cellar using alternative assets. * @param depositAsset the asset to deposit * @param assets amount of depositAsset to deposit * @param receiver address to receive the shares */ function multiAssetDeposit( ERC20 depositAsset, uint256 assets, address receiver ) public nonReentrant returns (uint256 shares) { // Convert assets from depositAsset to asset. ( uint256 assetsConvertedToAsset, uint256 assetsConvertedToAssetWithFeeRemoved, uint32 position ) = _getMultiAssetDepositData(depositAsset, assets); shares = _deposit( depositAsset, assets, assetsConvertedToAsset, assetsConvertedToAssetWithFeeRemoved, position, receiver ); emit MultiAssetDeposit(msg.sender, receiver, address(depositAsset), assets, shares); } //============================== PREVIEW FUNCTIONS =============================== /** * @notice Preview function to see how many shares a multi asset deposit will give user. */ function previewMultiAssetDeposit(ERC20 depositAsset, uint256 assets) external view returns (uint256 shares) { // Convert assets from depositAsset to asset. (uint256 assetsConvertedToAsset, uint256 assetsConvertedToAssetWithFeeRemoved, ) = _getMultiAssetDepositData( depositAsset, assets ); (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true); shares = _convertToShares( assetsConvertedToAssetWithFeeRemoved, _totalAssets + (assetsConvertedToAsset - assetsConvertedToAssetWithFeeRemoved), _totalSupply ); } //============================== HELPER FUNCTIONS =============================== /** * @notice Helper function to fulfill normal deposits and multi asset deposits. */ function _deposit( ERC20 depositAsset, uint256 assets, uint256 assetsConvertedToAsset, uint256 assetsConvertedToAssetWithFeeRemoved, uint32 position, address receiver ) internal returns (uint256 shares) { // Use `_calculateTotalAssetsOrTotalAssetsWithdrawable` instead of totalAssets bc re-entrancy is already checked in this function. (uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true); // Perform share calculation using assetsConvertedToAssetWithFeeRemoved. // Check for rounding error since we round down in previewDeposit. // NOTE for totalAssets, we add the delta between assetsConvertedToAsset, and assetsConvertedToAssetWithFeeRemoved, so that the fee the caller pays // to join with the alternative asset is factored into share price calculation. if ( (shares = _convertToShares( assetsConvertedToAssetWithFeeRemoved, _totalAssets + (assetsConvertedToAsset - assetsConvertedToAssetWithFeeRemoved), _totalSupply )) == 0 ) revert Cellar__ZeroShares(); if ((_totalSupply + shares) > shareSupplyCap) revert Cellar__ShareSupplyCapExceeded(); // _enter into holding position but passing in actual assets. _enter(depositAsset, position, assets, shares, receiver); } /** * @notice Helper function to verify asset is supported for multi asset deposit, * convert assets from depositAsset to asset, and account for alternative asset fee. */ function _getMultiAssetDepositData( ERC20 depositAsset, uint256 assets ) internal view returns (uint256 assetsConvertedToAsset, uint256 assetsConvertedToAssetWithFeeRemoved, uint32 position) { AlternativeAssetData memory assetData = alternativeAssetData[depositAsset]; if (!assetData.isSupported) revert CellarWithMultiAssetDeposit__AlternativeAssetNotSupported(); // Convert assets from depositAsset to asset. assetsConvertedToAsset = priceRouter.getValue(depositAsset, assets, asset); // Collect alternative asset fee. assetsConvertedToAssetWithFeeRemoved = assetsConvertedToAsset.mulDivDown(1e8 - assetData.depositFee, 1e8); position = assetData.holdingPosition; } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; library Math { /** * @notice Substract with a floor of 0 for the result. */ function subMinZero(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x - y : 0; } /** * @notice Used to change the decimals of precision used for an amount. */ function changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) { if (fromDecimals == toDecimals) { return amount; } else if (fromDecimals < toDecimals) { return amount * 10 ** (toDecimals - fromDecimals); } else { return amount / 10 ** (fromDecimals - toDecimals); } } // ===================================== OPENZEPPELIN'S MATH ===================================== function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } // ================================= SOLMATE's FIXEDPOINTMATHLIB ================================= uint256 public 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 mulDivDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // First, divide z - 1 by the denominator and add 1. // We allow z - 1 to underflow if z is 0, because we multiply the // end result by 0 if z is zero, ensuring we return 0 if z is zero. z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1)) } } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; import {SafeTransferLib} from "../utils/SafeTransferLib.sol"; import {FixedPointMathLib} from "../utils/FixedPointMathLib.sol"; /// @notice Minimal ERC4626 tokenized Vault implementation. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol) abstract contract ERC4626 is ERC20 { using SafeTransferLib for ERC20; using FixedPointMathLib for uint256; /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); event Withdraw( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); /*////////////////////////////////////////////////////////////// IMMUTABLES //////////////////////////////////////////////////////////////*/ ERC20 public immutable asset; constructor( ERC20 _asset, string memory _name, string memory _symbol ) ERC20(_name, _symbol, _asset.decimals()) { asset = _asset; } /*////////////////////////////////////////////////////////////// DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) { // Check for rounding error since we round down in previewDeposit. require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES"); // Need to transfer before minting or ERC777s could reenter. asset.safeTransferFrom(msg.sender, address(this), assets); _mint(receiver, shares); emit Deposit(msg.sender, receiver, assets, shares); afterDeposit(assets, shares); } function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) { assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up. // Need to transfer before minting or ERC777s could reenter. asset.safeTransferFrom(msg.sender, address(this), assets); _mint(receiver, shares); emit Deposit(msg.sender, receiver, assets, shares); afterDeposit(assets, shares); } function withdraw( uint256 assets, address receiver, address owner ) public virtual returns (uint256 shares) { shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up. if (msg.sender != owner) { uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } beforeWithdraw(assets, shares); _burn(owner, shares); emit Withdraw(msg.sender, receiver, owner, assets, shares); asset.safeTransfer(receiver, assets); } function redeem( uint256 shares, address receiver, address owner ) public virtual returns (uint256 assets) { if (msg.sender != owner) { uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } // Check for rounding error since we round down in previewRedeem. require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS"); beforeWithdraw(assets, shares); _burn(owner, shares); emit Withdraw(msg.sender, receiver, owner, assets, shares); asset.safeTransfer(receiver, assets); } /*////////////////////////////////////////////////////////////// ACCOUNTING LOGIC //////////////////////////////////////////////////////////////*/ function totalAssets() public view virtual returns (uint256); function convertToShares(uint256 assets) public view virtual returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets()); } function convertToAssets(uint256 shares) public view virtual returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply); } function previewDeposit(uint256 assets) public view virtual returns (uint256) { return convertToShares(assets); } function previewMint(uint256 shares) public view virtual returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply); } function previewWithdraw(uint256 assets) public view virtual returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets()); } function previewRedeem(uint256 shares) public view virtual returns (uint256) { return convertToAssets(shares); } /*////////////////////////////////////////////////////////////// DEPOSIT/WITHDRAWAL LIMIT LOGIC //////////////////////////////////////////////////////////////*/ function maxDeposit(address) public view virtual returns (uint256) { return type(uint256).max; } function maxMint(address) public view virtual returns (uint256) { return type(uint256).max; } function maxWithdraw(address owner) public view virtual returns (uint256) { return convertToAssets(balanceOf[owner]); } function maxRedeem(address owner) public view virtual returns (uint256) { return balanceOf[owner]; } /*////////////////////////////////////////////////////////////// INTERNAL HOOKS LOGIC //////////////////////////////////////////////////////////////*/ function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {} function afterDeposit(uint256 assets, uint256 shares) internal virtual {} }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller. library SafeTransferLib { /*////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(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) } require(success, "ETH_TRANSFER_FAILED"); } /*////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 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), from) // Append the "from" argument. mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. 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) ) } require(success, "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 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), to) // Append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. 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) ) } require(success, "TRANSFER_FAILED"); } function safeApprove( ERC20 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, 0x095ea7b300000000000000000000000000000000000000000000000000000000) mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. 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) ) } require(success, "APPROVE_FAILED"); } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner, spender, value, nonces[owner]++, deadline ) ) ) ), v, r, s ); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Cellar } from "src/base/Cellar.sol"; import { ERC20 } from "@solmate/tokens/ERC20.sol"; import { BaseAdaptor } from "src/modules/adaptors/BaseAdaptor.sol"; import { PriceRouter } from "src/modules/price-router/PriceRouter.sol"; contract Registry is Ownable { // ============================================= ADDRESS CONFIG ============================================= /** * @notice Emitted when the address of a contract is changed. * @param id value representing the unique ID tied to the changed contract * @param oldAddress address of the contract before the change * @param newAddress address of the contract after the contract */ event AddressChanged(uint256 indexed id, address oldAddress, address newAddress); /** * @notice Attempted to set the address of a contract that is not registered. * @param id id of the contract that is not registered */ error Registry__ContractNotRegistered(uint256 id); /** * @notice Emitted when depositor privilege changes. * @param depositor depositor address * @param state the new state of the depositor privilege */ event DepositorOnBehalfChanged(address depositor, bool state); /** * @notice The unique ID that the next registered contract will have. */ uint256 public nextId; /** * @notice Get the address associated with an id. */ mapping(uint256 => address) public getAddress; /** * @notice In order for an address to make deposits on behalf of users they must be approved. */ mapping(address => bool) public approvedForDepositOnBehalf; /** * @notice toggles a depositors ability to deposit into cellars on behalf of users. */ function setApprovedForDepositOnBehalf(address depositor, bool state) external onlyOwner { approvedForDepositOnBehalf[depositor] = state; emit DepositorOnBehalfChanged(depositor, state); } /** * @notice Set the address of the contract at a given id. */ function setAddress(uint256 id, address newAddress) external { if (id > 0) { _checkOwner(); if (id >= nextId) revert Registry__ContractNotRegistered(id); } else { if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId(); } emit AddressChanged(id, getAddress[id], newAddress); getAddress[id] = newAddress; } // ============================================= INITIALIZATION ============================================= /** * @param gravityBridge address of GravityBridge contract * @param swapRouter address of SwapRouter contract * @param priceRouter address of PriceRouter contract */ constructor(address newOwner, address gravityBridge, address swapRouter, address priceRouter) Ownable() { _register(gravityBridge); _register(swapRouter); _register(priceRouter); transferOwnership(newOwner); } // ============================================ REGISTER CONFIG ============================================ /** * @notice Emitted when a new contract is registered. * @param id value representing the unique ID tied to the new contract * @param newContract address of the new contract */ event Registered(uint256 indexed id, address indexed newContract); /** * @notice Register the address of a new contract. * @param newContract address of the new contract to register */ function register(address newContract) external onlyOwner { _register(newContract); } function _register(address newContract) internal { getAddress[nextId] = newContract; emit Registered(nextId, newContract); nextId++; } // ============================================= ADDRESS 0 LOGIC ============================================= /** * Address 0 is the address of the gravity bridge, and special abilities that the owner does not have. * - It can change what address is stored at address 0. * - It can change the owner of this contract. */ /** * @notice Emitted when an ownership transition is started. */ event OwnerTransitionStarted(address newOwner, uint256 startTime); /** * @notice Emitted when an ownership transition is cancelled. */ event OwnerTransitionCancelled(); /** * @notice Emitted when an ownership transition is completed. */ event OwnerTransitionComplete(address newOwner); /** * @notice Attempted to call a function intended for Zero Id address. */ error Registry__OnlyCallableByZeroId(); /** * @notice Attempted to transition owner to the zero address. */ error Registry__NewOwnerCanNotBeZero(); /** * @notice Attempted to perform a restricted action while ownership transition is pending. */ error Registry__TransitionPending(); /** * @notice Attempted to cancel or complete a transition when one is not active. */ error Registry__TransitionNotPending(); /** * @notice Attempted to call `completeTransition` from an address that is not the pending owner. */ error Registry__OnlyCallableByPendingOwner(); /** * @notice The amount of time it takes for an ownership transition to work. */ uint256 public constant TRANSITION_PERIOD = 7 days; /** * @notice The Pending Owner, that becomes the owner after the transition period, and they call `completeTransition`. */ address public pendingOwner; /** * @notice The starting time stamp of the transition. */ uint256 public transitionStart; /** * @notice Allows Zero Id address to set a new owner, after the transition period is up. */ function transitionOwner(address newOwner) external { if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId(); if (pendingOwner != address(0)) revert Registry__TransitionPending(); if (newOwner == address(0)) revert Registry__NewOwnerCanNotBeZero(); pendingOwner = newOwner; transitionStart = block.timestamp; } /** * @notice Allows Zero Id address to cancel an ongoing owner transition. */ function cancelTransition() external { if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId(); if (pendingOwner == address(0)) revert Registry__TransitionNotPending(); pendingOwner = address(0); transitionStart = 0; } /** * @notice Allows pending owner to complete the ownership transition. */ function completeTransition() external { if (pendingOwner == address(0)) revert Registry__TransitionNotPending(); if (msg.sender != pendingOwner) revert Registry__OnlyCallableByPendingOwner(); if (block.timestamp < transitionStart + TRANSITION_PERIOD) revert Registry__TransitionPending(); _transferOwnership(pendingOwner); pendingOwner = address(0); transitionStart = 0; } /** * @notice Extends OZ Ownable `_checkOwner` function to block owner calls, if there is an ongoing transition. */ function _checkOwner() internal view override { require(owner() == _msgSender(), "Ownable: caller is not the owner"); if (transitionStart != 0) revert Registry__TransitionPending(); } // ============================================ PAUSE LOGIC ============================================ /** * @notice Emitted when a target is paused. */ event TargetPaused(address target); /** * @notice Emitted when a target is unpaused. */ event TargetUnpaused(address target); /** * @notice Attempted to unpause a target that was not paused. */ error Registry__TargetNotPaused(address target); /** * @notice Attempted to pause a target that was already paused. */ error Registry__TargetAlreadyPaused(address target); /** * @notice Mapping stores whether or not a cellar is paused. */ mapping(address => bool) public isCallerPaused; /** * @notice Allows multisig to pause multiple cellars in a single call. */ function batchPause(address[] calldata targets) external onlyOwner { for (uint256 i; i < targets.length; ++i) _pauseTarget(targets[i]); } /** * @notice Allows multisig to unpause multiple cellars in a single call. */ function batchUnpause(address[] calldata targets) external onlyOwner { for (uint256 i; i < targets.length; ++i) _unpauseTarget(targets[i]); } /** * @notice Helper function to pause some target. */ function _pauseTarget(address target) internal { if (isCallerPaused[target]) revert Registry__TargetAlreadyPaused(target); isCallerPaused[target] = true; emit TargetPaused(target); } /** * @notice Helper function to unpause some target. */ function _unpauseTarget(address target) internal { if (!isCallerPaused[target]) revert Registry__TargetNotPaused(target); isCallerPaused[target] = false; emit TargetUnpaused(target); } // ============================================ ADAPTOR LOGIC ============================================ /** * @notice Attempted to trust an adaptor with non unique identifier. */ error Registry__IdentifierNotUnique(); /** * @notice Attempted to use an untrusted adaptor. */ error Registry__AdaptorNotTrusted(address adaptor); /** * @notice Attempted to trust an already trusted adaptor. */ error Registry__AdaptorAlreadyTrusted(address adaptor); /** * @notice Maps an adaptor address to bool indicating whether it has been set up in the registry. */ mapping(address => bool) public isAdaptorTrusted; /** * @notice Maps an adaptors identfier to bool, to track if the identifier is unique wrt the registry. */ mapping(bytes32 => bool) public isIdentifierUsed; /** * @notice Trust an adaptor to be used by cellars * @param adaptor address of the adaptor to trust */ function trustAdaptor(address adaptor) external onlyOwner { if (isAdaptorTrusted[adaptor]) revert Registry__AdaptorAlreadyTrusted(adaptor); bytes32 identifier = BaseAdaptor(adaptor).identifier(); if (isIdentifierUsed[identifier]) revert Registry__IdentifierNotUnique(); isAdaptorTrusted[adaptor] = true; isIdentifierUsed[identifier] = true; } /** * @notice Allows registry to distrust adaptors. * @dev Doing so prevents Cellars from adding this adaptor to their catalogue. */ function distrustAdaptor(address adaptor) external onlyOwner { if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor); // Set trust to false. isAdaptorTrusted[adaptor] = false; // We are NOT resetting `isIdentifierUsed` because if this adaptor is distrusted, then something needs // to change about the new one being re-trusted. } /** * @notice Reverts if `adaptor` is not trusted by the registry. */ function revertIfAdaptorIsNotTrusted(address adaptor) external view { if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor); } // ============================================ POSITION LOGIC ============================================ /** * @notice stores data related to Cellar positions. * @param adaptors address of the adaptor to use for this position * @param isDebt bool indicating whether this position takes on debt or not * @param adaptorData arbitrary data needed to correclty set up a position * @param configurationData arbitrary data settable by strategist to change cellar <-> adaptor interaction */ struct PositionData { address adaptor; bool isDebt; bytes adaptorData; bytes configurationData; } /** * @notice Emitted when a new position is added to the registry. * @param id the positions id * @param adaptor address of the adaptor this position uses * @param isDebt bool indicating whether this position takes on debt or not * @param adaptorData arbitrary bytes used to configure this position */ event Registry__PositionTrusted(uint32 id, address adaptor, bool isDebt, bytes adaptorData); /** * @notice Emitted when a position is distrusted. * @param id the positions id */ event Registry__PositionDistrusted(uint32 id); /** * @notice Attempted to trust a position not being used. * @param position address of the invalid position */ error Registry__PositionPricingNotSetUp(address position); /** * @notice Attempted to add a position with bad input values. */ error Registry__InvalidPositionInput(); /** * @notice Attempted to add a position that does not exist. */ error Registry__PositionDoesNotExist(); /** * @notice Attempted to add a position that is not trusted. */ error Registry__PositionIsNotTrusted(uint32 position); /** * @notice Addresses of the positions currently used by the cellar. */ uint256 public constant PRICE_ROUTER_REGISTRY_SLOT = 2; /** * @notice Maps a position hash to a position Id. * @dev can be used by adaptors to verify that a certain position is open during Cellar `callOnAdaptor` calls. */ mapping(bytes32 => uint32) public getPositionHashToPositionId; /** * @notice Maps a position id to its position data. * @dev used by Cellars when adding new positions. */ mapping(uint32 => PositionData) public getPositionIdToPositionData; /** * @notice Maps a position to a bool indicating whether or not it is trusted. */ mapping(uint32 => bool) public isPositionTrusted; /** * @notice Trust a position to be used by the cellar. * @param positionId the position id of the newly added position * @param adaptor the adaptor address this position uses * @param adaptorData arbitrary bytes used to configure this position */ function trustPosition(uint32 positionId, address adaptor, bytes memory adaptorData) external onlyOwner { bytes32 identifier = BaseAdaptor(adaptor).identifier(); bool isDebt = BaseAdaptor(adaptor).isDebt(); bytes32 positionHash = keccak256(abi.encode(identifier, isDebt, adaptorData)); if (positionId == 0) revert Registry__InvalidPositionInput(); // Make sure positionId is not already in use. PositionData storage pData = getPositionIdToPositionData[positionId]; if (pData.adaptor != address(0)) revert Registry__InvalidPositionInput(); // Check that... // `adaptor` is a non zero address // position has not been already set up if (adaptor == address(0) || getPositionHashToPositionId[positionHash] != 0) revert Registry__InvalidPositionInput(); if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor); // Set position data. pData.adaptor = adaptor; pData.isDebt = isDebt; pData.adaptorData = adaptorData; pData.configurationData = abi.encode(0); // Globally trust the position. isPositionTrusted[positionId] = true; getPositionHashToPositionId[positionHash] = positionId; // Check that assets position uses are supported for pricing operations. ERC20[] memory assets = BaseAdaptor(adaptor).assetsUsed(adaptorData); PriceRouter priceRouter = PriceRouter(getAddress[PRICE_ROUTER_REGISTRY_SLOT]); for (uint256 i; i < assets.length; i++) { if (!priceRouter.isSupported(assets[i])) revert Registry__PositionPricingNotSetUp(address(assets[i])); } emit Registry__PositionTrusted(positionId, adaptor, isDebt, adaptorData); } /** * @notice Allows registry to distrust positions. * @dev Doing so prevents Cellars from adding this position to their catalogue, * and adding the position to their tracked arrays. */ function distrustPosition(uint32 positionId) external onlyOwner { if (!isPositionTrusted[positionId]) revert Registry__PositionIsNotTrusted(positionId); isPositionTrusted[positionId] = false; emit Registry__PositionDistrusted(positionId); } /** * @notice Called by Cellars to add a new position to themselves. * @param positionId the id of the position the cellar wants to add * @return adaptor the address of the adaptor, isDebt bool indicating whether position is * debt or not, and adaptorData needed to interact with position */ function addPositionToCellar( uint32 positionId ) external view returns (address adaptor, bool isDebt, bytes memory adaptorData) { if (positionId == 0) revert Registry__PositionDoesNotExist(); PositionData memory positionData = getPositionIdToPositionData[positionId]; if (positionData.adaptor == address(0)) revert Registry__PositionDoesNotExist(); revertIfPositionIsNotTrusted(positionId); return (positionData.adaptor, positionData.isDebt, positionData.adaptorData); } /** * @notice Reverts if `positionId` is not trusted by the registry. */ function revertIfPositionIsNotTrusted(uint32 positionId) public view { if (!isPositionTrusted[positionId]) revert Registry__PositionIsNotTrusted(positionId); } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol"; import { ERC20 } from "@solmate/tokens/ERC20.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IChainlinkAggregator } from "src/interfaces/external/IChainlinkAggregator.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { Math } from "src/utils/Math.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Extension } from "src/modules/price-router/Extensions/Extension.sol"; import { Registry } from "src/Registry.sol"; import { UniswapV3Pool } from "src/interfaces/external/UniswapV3Pool.sol"; import { OracleLibrary } from "@uniswapV3P/libraries/OracleLibrary.sol"; /** * @title Sommelier Price Router * @notice Provides a universal interface allowing Sommelier contracts to retrieve secure pricing * data from Chainlink. * @author crispymangoes */ contract PriceRouter is Ownable { using SafeTransferLib for ERC20; using SafeCast for int256; using Math for uint256; using Address for address; event AddAsset(address indexed asset); event IntentToEditAsset( address asset, AssetSettings _settings, bytes _storage, bytes32 editHash, uint256 assetEditableAt ); event EditAssetCancelled(address asset, bytes32 editHash); event EditAssetComplete(address asset, bytes32 editHash); Registry public immutable registry; ERC20 public immutable WETH; constructor(address newOwner, Registry _registry, ERC20 _weth) { registry = _registry; WETH = _weth; transferOwnership(newOwner); } // =========================================== ASSETS CONFIG =========================================== /** * @notice Bare minimum settings all derivatives support. * @param derivative the derivative used to price the asset * @param source the address used to price the asset */ struct AssetSettings { uint8 derivative; address source; } /** * @notice Mapping between an asset to price and its `AssetSettings`. */ mapping(ERC20 => AssetSettings) public getAssetSettings; // ======================================= OWNERSHIP TRANSISITION ======================================= /** * @notice Emitted when an ownership transition is started. */ event OwnerTransitionStarted(address newOwner, uint256 startTime); /** * @notice Emitted when an ownership transition is cancelled. */ event OwnerTransitionCancelled(); /** * @notice Emitted when an ownership transition is completed. */ event OwnerTransitionComplete(address newOwner); /** * @notice Attempted to call a function intended for Zero Id address. */ error PriceRouter__OnlyCallableByZeroId(); /** * @notice Attempted to transition owner to the zero address. */ error PriceRouter__NewOwnerCanNotBeZero(); /** * @notice Attempted to perform a restricted action while ownership transition is pending. */ error PriceRouter__TransitionPending(); /** * @notice Attempted to cancel or complete a transition when one is not active. */ error PriceRouter__TransitionNotPending(); /** * @notice Attempted to call `completeTransition` from an address that is not the pending owner. */ error PriceRouter__OnlyCallableByPendingOwner(); /** * @notice The amount of time it takes for an ownership transition to work. */ uint256 public constant TRANSITION_PERIOD = 7 days; /** * @notice The Pending Owner, that becomes the owner after the transition period, and they call `completeTransition`. */ address public pendingOwner; /** * @notice The starting time stamp of the transition. */ uint256 public transitionStart; /** * @notice Allows Zero Id address to set a new owner, after the transition period is up. */ function transitionOwner(address newOwner) external { if (msg.sender != registry.getAddress(0)) revert PriceRouter__OnlyCallableByZeroId(); if (pendingOwner != address(0)) revert PriceRouter__TransitionPending(); if (newOwner == address(0)) revert PriceRouter__NewOwnerCanNotBeZero(); pendingOwner = newOwner; transitionStart = block.timestamp; } /** * @notice Allows Zero Id address to cancel an ongoing owner transition. */ function cancelTransition() external { if (msg.sender != registry.getAddress(0)) revert PriceRouter__OnlyCallableByZeroId(); if (pendingOwner == address(0)) revert PriceRouter__TransitionNotPending(); pendingOwner = address(0); transitionStart = 0; } /** * @notice Allows pending owner to complete the ownership transition. */ function completeTransition() external { if (pendingOwner == address(0)) revert PriceRouter__TransitionNotPending(); if (msg.sender != pendingOwner) revert PriceRouter__OnlyCallableByPendingOwner(); if (block.timestamp < transitionStart + TRANSITION_PERIOD) revert PriceRouter__TransitionPending(); _transferOwnership(pendingOwner); pendingOwner = address(0); transitionStart = 0; } /** * @notice Extends OZ Ownable `_checkOwner` function to block owner calls, if there is an ongoing transition. */ function _checkOwner() internal view override { require(owner() == _msgSender(), "Ownable: caller is not the owner"); if (transitionStart != 0) revert PriceRouter__TransitionPending(); } // ======================================= ASSET OPERATIONS ======================================= /** * @notice Attempted to set a minimum price below the Chainlink minimum price (with buffer). * @param minPrice minimum price attempted to set * @param bufferedMinPrice minimum price that can be set including buffer */ error PriceRouter__InvalidMinPrice(uint256 minPrice, uint256 bufferedMinPrice); /** * @notice Attempted to set a maximum price above the Chainlink maximum price (with buffer). * @param maxPrice maximum price attempted to set * @param bufferedMaxPrice maximum price that can be set including buffer */ error PriceRouter__InvalidMaxPrice(uint256 maxPrice, uint256 bufferedMaxPrice); /** * @notice Attempted to add an invalid asset. * @param asset address of the invalid asset */ error PriceRouter__InvalidAsset(address asset); /** * @notice Attempted to add an asset that is already supported. */ error PriceRouter__AssetAlreadyAdded(address asset); /** * @notice Attempted to edit an asset that is not supported. */ error PriceRouter__AssetNotAdded(address asset); /** * @notice Attempted to edit an asset that is not editable. */ error PriceRouter__AssetNotEditable(address asset); /** * @notice Attempted to cancel the editing of an asset that is not pending edit. */ error PriceRouter__AssetNotPendingEdit(address asset); /** * @notice Attempted to add an asset, but actual answer was outside range of expectedAnswer. */ error PriceRouter__BadAnswer(uint256 answer, uint256 expectedAnswer); /** * @notice Attempted to perform an operation using an unknown derivative. */ error PriceRouter__UnknownDerivative(uint8 unknownDerivative); /** * @notice Attempted to add an asset with invalid min/max prices. * @param min price * @param max price */ error PriceRouter__MinPriceGreaterThanMaxPrice(uint256 min, uint256 max); /** * @notice The allowed deviation between the expected answer vs the actual answer. */ uint256 public constant EXPECTED_ANSWER_DEVIATION = 0.02e18; /** * @notice The amount of time that must pass between owner calling `startEditAsset`, and `completeEditAsset`. */ uint64 public constant EDIT_ASSET_DELAY = 7 days; /** * @notice Stores the timestamp when an asset can be editted. */ mapping(bytes32 => uint256) public assetEditableTimestamp; /** * @notice Allows owner to add assets to the price router. * @dev Performs a sanity check by comparing the price router computed price to * a user input `_expectedAnswer`. * @param _asset the asset to add to the pricing router * @param _settings the settings for `_asset` * @dev The `derivative` value in settings MUST be non zero. * @param _storage arbitrary bytes data used to configure `_asset` pricing * @param _expectedAnswer the expected answer for the asset from `_getPriceInUSD` */ function addAsset( ERC20 _asset, AssetSettings memory _settings, bytes memory _storage, uint256 _expectedAnswer ) external onlyOwner { // Check that asset is not already added. if (getAssetSettings[_asset].derivative > 0) revert PriceRouter__AssetAlreadyAdded(address(_asset)); _updateAsset(_asset, _settings, _storage, _expectedAnswer); emit AddAsset(address(_asset)); } /** * @notice Allows owner to start the edit asset process. * @dev Saves a hash of the inputs, and maps it to the timestamp when `_asset` is editable. * @param _asset the asset to edit in the pricing router * @param _settings the settings for `_asset` * @dev The `derivative` value in settings MUST be non zero. * @param _storage arbitrary bytes data used to configure `_asset` pricing */ function startEditAsset(ERC20 _asset, AssetSettings memory _settings, bytes memory _storage) external onlyOwner { // Make sure the asset has been added. if (getAssetSettings[_asset].derivative == 0) revert PriceRouter__AssetNotAdded(address(_asset)); bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage)); uint256 assetEditableAt = block.timestamp + EDIT_ASSET_DELAY; assetEditableTimestamp[editHash] = assetEditableAt; emit IntentToEditAsset(address(_asset), _settings, _storage, editHash, assetEditableAt); } /** * @notice Once `EDIT_ASSET_DELAY` has passed, `_asset` is now editable using the * same inputs given to `startEditAsset`. * @param _asset the asset to finish editing in the pricing router * @param _settings the settings for `_asset` * @dev The `derivative` value in settings MUST be non zero. * @param _storage arbitrary bytes data used to configure `_asset` pricing */ function completeEditAsset( ERC20 _asset, AssetSettings memory _settings, bytes memory _storage, uint256 _expectedAnswer ) external onlyOwner { bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage)); // Make sure asset can be edited. uint256 assetEditableAt = assetEditableTimestamp[editHash]; if (assetEditableAt == 0 || block.timestamp < assetEditableAt) revert PriceRouter__AssetNotEditable(address(_asset)); // Reset edit timestamp. assetEditableTimestamp[editHash] = 0; // Edit the asset. _updateAsset(_asset, _settings, _storage, _expectedAnswer); emit EditAssetComplete(address(_asset), editHash); } /** * @notice Cancel a pending edit for `_asset`. * @param _asset the asset to cancel editing of in the pricing router * @param _settings the settings for `_asset` * @dev The `derivative` value in settings MUST be non zero. * @param _storage arbitrary bytes data used to configure `_asset` pricing */ function cancelEditAsset(ERC20 _asset, AssetSettings memory _settings, bytes memory _storage) external onlyOwner { bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage)); // Make sure asset is pending edit. uint256 assetEditableAt = assetEditableTimestamp[editHash]; if (assetEditableAt == 0) revert PriceRouter__AssetNotPendingEdit(address(_asset)); assetEditableTimestamp[editHash] = 0; emit EditAssetCancelled(address(_asset), editHash); } /** * @notice Helper function to update an `_asset`s configuration. * @param _asset the asset to update in the pricing router * @param _settings the settings for `_asset` * @dev The `derivative` value in settings MUST be non zero. * @param _storage arbitrary bytes data used to configure `_asset` pricing */ function _updateAsset( ERC20 _asset, AssetSettings memory _settings, bytes memory _storage, uint256 _expectedAnswer ) internal { if (address(_asset) == address(0)) revert PriceRouter__InvalidAsset(address(_asset)); // Zero is an invalid derivative. if (_settings.derivative == 0) revert PriceRouter__UnknownDerivative(_settings.derivative); // Call setup function for appropriate derivative. if (_settings.derivative == 1) { _setupPriceForChainlinkDerivative(_asset, _settings.source, _storage); } else if (_settings.derivative == 2) { _setupPriceForTwapDerivative(_asset, _settings.source, _storage); } else if (_settings.derivative == 3) { Extension(_settings.source).setupSource(_asset, _storage); } else revert PriceRouter__UnknownDerivative(_settings.derivative); // Check `_getPriceInUSD` against `_expectedAnswer`. uint256 minAnswer = _expectedAnswer.mulWadDown((1e18 - EXPECTED_ANSWER_DEVIATION)); uint256 maxAnswer = _expectedAnswer.mulWadDown((1e18 + EXPECTED_ANSWER_DEVIATION)); getAssetSettings[_asset] = _settings; uint256 answer = _getPriceInUSD(_asset, _settings); if (answer < minAnswer || answer > maxAnswer) revert PriceRouter__BadAnswer(answer, _expectedAnswer); } /** * @notice return bool indicating whether or not an asset has been set up. * @dev Since `addAsset` enforces the derivative is non zero, checking if the stored setting * is nonzero is sufficient to see if the asset is set up. */ function isSupported(ERC20 asset) external view returns (bool) { return getAssetSettings[asset].derivative > 0; } // ======================================= PRICING OPERATIONS ======================================= /** * @notice Get `asset` price in USD. * @dev Returns price in USD with 8 decimals. */ function getPriceInUSD(ERC20 asset) external view returns (uint256) { AssetSettings memory assetSettings = getAssetSettings[asset]; return _getPriceInUSD(asset, assetSettings); } /** * @notice Get multiple `asset` prices in USD. * @dev Returns array of prices in USD with 8 decimals. */ function getPricesInUSD(ERC20[] calldata assets) external view returns (uint256[] memory prices) { prices = new uint256[](assets.length); for (uint256 i; i < assets.length; ++i) { AssetSettings memory assetSettings = getAssetSettings[assets[i]]; prices[i] = _getPriceInUSD(assets[i], assetSettings); } } /** * @notice Get the value of an asset in terms of another asset. * @param baseAsset address of the asset to get the price of in terms of the quote asset * @param amount amount of the base asset to price * @param quoteAsset address of the asset that the base asset is priced in terms of * @return value value of the amount of base assets specified in terms of the quote asset */ function getValue(ERC20 baseAsset, uint256 amount, ERC20 quoteAsset) external view returns (uint256 value) { AssetSettings memory baseSettings = getAssetSettings[baseAsset]; AssetSettings memory quoteSettings = getAssetSettings[quoteAsset]; if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset)); if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset)); uint256 priceBaseUSD = _getPriceInUSD(baseAsset, baseSettings); uint256 priceQuoteUSD = _getPriceInUSD(quoteAsset, quoteSettings); value = _getValueInQuote(priceBaseUSD, priceQuoteUSD, baseAsset.decimals(), quoteAsset.decimals(), amount); } /** * @notice Helper function that compares `_getValues` between input 0 and input 1. */ function getValuesDelta( ERC20[] calldata baseAssets0, uint256[] calldata amounts0, ERC20[] calldata baseAssets1, uint256[] calldata amounts1, ERC20 quoteAsset ) external view returns (uint256) { uint256 value0 = _getValues(baseAssets0, amounts0, quoteAsset); uint256 value1 = _getValues(baseAssets1, amounts1, quoteAsset); return value0 - value1; } /** * @notice Helper function that determines the value of assets using `_getValues`. */ function getValues( ERC20[] calldata baseAssets, uint256[] calldata amounts, ERC20 quoteAsset ) external view returns (uint256) { return _getValues(baseAssets, amounts, quoteAsset); } /** * @notice Get the exchange rate between two assets. * @param baseAsset address of the asset to get the exchange rate of in terms of the quote asset * @param quoteAsset address of the asset that the base asset is exchanged for * @return exchangeRate rate of exchange between the base asset and the quote asset */ function getExchangeRate(ERC20 baseAsset, ERC20 quoteAsset) public view returns (uint256 exchangeRate) { AssetSettings memory baseSettings = getAssetSettings[baseAsset]; AssetSettings memory quoteSettings = getAssetSettings[quoteAsset]; if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset)); if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset)); exchangeRate = _getExchangeRate(baseAsset, baseSettings, quoteAsset, quoteSettings, quoteAsset.decimals()); } /** * @notice Get the exchange rates between multiple assets and another asset. * @param baseAssets addresses of the assets to get the exchange rates of in terms of the quote asset * @param quoteAsset address of the asset that the base assets are exchanged for * @return exchangeRates rate of exchange between the base assets and the quote asset */ function getExchangeRates( ERC20[] memory baseAssets, ERC20 quoteAsset ) external view returns (uint256[] memory exchangeRates) { uint8 quoteAssetDecimals = quoteAsset.decimals(); AssetSettings memory quoteSettings = getAssetSettings[quoteAsset]; if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset)); uint256 numOfAssets = baseAssets.length; exchangeRates = new uint256[](numOfAssets); for (uint256 i; i < numOfAssets; ++i) { AssetSettings memory baseSettings = getAssetSettings[baseAssets[i]]; if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAssets[i])); exchangeRates[i] = _getExchangeRate( baseAssets[i], baseSettings, quoteAsset, quoteSettings, quoteAssetDecimals ); } } // =========================================== HELPER FUNCTIONS =========================================== /** * @notice Attempted to update the asset to one that is not supported by the platform. * @param asset address of the unsupported asset */ error PriceRouter__UnsupportedAsset(address asset); /** * @notice Gets the exchange rate between a base and a quote asset * @param baseAsset the asset to convert into quoteAsset * @param quoteAsset the asset base asset is converted into * @return exchangeRate value of base asset in terms of quote asset */ function _getExchangeRate( ERC20 baseAsset, AssetSettings memory baseSettings, ERC20 quoteAsset, AssetSettings memory quoteSettings, uint8 quoteAssetDecimals ) internal view returns (uint256) { uint256 basePrice = _getPriceInUSD(baseAsset, baseSettings); uint256 quotePrice = _getPriceInUSD(quoteAsset, quoteSettings); uint256 exchangeRate = basePrice.mulDivDown(10 ** quoteAssetDecimals, quotePrice); return exchangeRate; } /** * @notice Helper function to get an assets price in USD. * @dev Returns price in USD with 8 decimals. */ function _getPriceInUSD(ERC20 asset, AssetSettings memory settings) internal view returns (uint256) { _runPreFlightCheck(); // Call get price function using appropriate derivative. uint256 price; if (settings.derivative == 1) { price = _getPriceForChainlinkDerivative(asset, settings.source); } else if (settings.derivative == 2) { price = _getPriceForTwapDerivative(asset, settings.source); } else if (settings.derivative == 3) { price = Extension(settings.source).getPriceInUSD(asset); } else revert PriceRouter__UnknownDerivative(settings.derivative); return price; } /** * @notice If any safety checks needs to be run before pricing operations, they should be added here. */ function _runPreFlightCheck() internal view virtual {} /** * @notice math function that preserves precision by multiplying the amountBase before dividing. * @param priceBaseUSD the base asset price in USD * @param priceQuoteUSD the quote asset price in USD * @param baseDecimals the base asset decimals * @param quoteDecimals the quote asset decimals * @param amountBase the amount of base asset */ function _getValueInQuote( uint256 priceBaseUSD, uint256 priceQuoteUSD, uint8 baseDecimals, uint8 quoteDecimals, uint256 amountBase ) internal pure returns (uint256 valueInQuote) { // Get value in quote asset, but maintain as much precision as possible. // Cleaner equations below. // baseToUSD = amountBase * priceBaseUSD / 10**baseDecimals. // valueInQuote = baseToUSD * 10**quoteDecimals / priceQuoteUSD valueInQuote = amountBase.mulDivDown( (priceBaseUSD * 10 ** quoteDecimals), (10 ** baseDecimals * priceQuoteUSD) ); } /** * @notice Attempted an operation with arrays of unequal lengths that were expected to be equal length. */ error PriceRouter__LengthMismatch(); /** * @notice Get the total value of multiple assets in terms of another asset. * @param baseAssets addresses of the assets to get the price of in terms of the quote asset * @param amounts amounts of each base asset to price * @param quoteAsset address of the assets that the base asset is priced in terms of * @return value total value of the amounts of each base assets specified in terms of the quote asset */ function _getValues( ERC20[] calldata baseAssets, uint256[] calldata amounts, ERC20 quoteAsset ) internal view returns (uint256) { if (baseAssets.length != amounts.length) revert PriceRouter__LengthMismatch(); uint256 quotePrice; { AssetSettings memory quoteSettings = getAssetSettings[quoteAsset]; if (quoteSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(quoteAsset)); quotePrice = _getPriceInUSD(quoteAsset, quoteSettings); } uint256 valueInQuote; uint8 quoteDecimals = quoteAsset.decimals(); for (uint256 i = 0; i < baseAssets.length; ++i) { // Skip zero amount values. if (amounts[i] == 0) continue; ERC20 baseAsset = baseAssets[i]; if (baseAsset == quoteAsset) valueInQuote += amounts[i]; else { uint256 basePrice; { AssetSettings memory baseSettings = getAssetSettings[baseAsset]; if (baseSettings.derivative == 0) revert PriceRouter__UnsupportedAsset(address(baseAsset)); basePrice = _getPriceInUSD(baseAsset, baseSettings); } valueInQuote += _getValueInQuote( basePrice, quotePrice, baseAsset.decimals(), quoteDecimals, amounts[i] ); } } return valueInQuote; } // =========================================== CHAINLINK PRICE DERIVATIVE ===========================================\ /** * @notice Stores data for Chainlink derivative assets. * @param max the max valid price of the asset * @param min the min valid price of the asset * @param heartbeat the max amount of time between price updates * @param inETH bool indicating whether the price feed is * denominated in ETH(true) or USD(false) */ struct ChainlinkDerivativeStorage { uint144 max; uint80 min; uint24 heartbeat; bool inETH; } /** * @notice Buffered min price exceedes 80 bits of data. */ error PriceRouter__BufferedMinOverflow(); /** * @notice Returns Chainlink Derivative Storage */ mapping(ERC20 => ChainlinkDerivativeStorage) public getChainlinkDerivativeStorage; /** * @notice If zero is specified for a Chainlink asset heartbeat, this value is used instead. */ uint24 public constant DEFAULT_HEART_BEAT = 1 days; /** * @notice Setup function for pricing Chainlink derivative assets. * @dev _source The address of the Chainlink Data feed. * @dev _storage A ChainlinkDerivativeStorage value defining valid prices. */ function _setupPriceForChainlinkDerivative(ERC20 _asset, address _source, bytes memory _storage) internal { ChainlinkDerivativeStorage memory parameters = abi.decode(_storage, (ChainlinkDerivativeStorage)); // Use Chainlink to get the min and max of the asset. IChainlinkAggregator aggregator = IChainlinkAggregator(IChainlinkAggregator(_source).aggregator()); uint256 minFromChainklink = uint256(uint192(aggregator.minAnswer())); uint256 maxFromChainlink = uint256(uint192(aggregator.maxAnswer())); // Add a ~10% buffer to minimum and maximum price from Chainlink because Chainlink can stop updating // its price before/above the min/max price. uint256 bufferedMinPrice = (minFromChainklink * 1.1e18) / 1e18; uint256 bufferedMaxPrice = (maxFromChainlink * 0.9e18) / 1e18; if (parameters.min == 0) { // Revert if bufferedMinPrice overflows because uint80 is too small to hold the minimum price, // and lowering it to uint80 is not safe because the price feed can stop being updated before // it actually gets to that lower price. if (bufferedMinPrice > type(uint80).max) revert PriceRouter__BufferedMinOverflow(); parameters.min = uint80(bufferedMinPrice); } else { if (parameters.min < bufferedMinPrice) revert PriceRouter__InvalidMinPrice(parameters.min, bufferedMinPrice); } if (parameters.max == 0) { //Do not revert even if bufferedMaxPrice is greater than uint144, because lowering it to uint144 max is more conservative. parameters.max = bufferedMaxPrice > type(uint144).max ? type(uint144).max : uint144(bufferedMaxPrice); } else { if (parameters.max > bufferedMaxPrice) revert PriceRouter__InvalidMaxPrice(parameters.max, bufferedMaxPrice); } if (parameters.min >= parameters.max) revert PriceRouter__MinPriceGreaterThanMaxPrice(parameters.min, parameters.max); parameters.heartbeat = parameters.heartbeat != 0 ? parameters.heartbeat : DEFAULT_HEART_BEAT; getChainlinkDerivativeStorage[_asset] = parameters; } /** * @notice Get the price of a Chainlink derivative in terms of USD. */ function _getPriceForChainlinkDerivative(ERC20 _asset, address _source) internal view returns (uint256) { ChainlinkDerivativeStorage memory parameters = getChainlinkDerivativeStorage[_asset]; IChainlinkAggregator aggregator = IChainlinkAggregator(_source); (, int256 _price, , uint256 _timestamp, ) = aggregator.latestRoundData(); uint256 price = _price.toUint256(); _checkPriceFeed(address(_asset), price, _timestamp, parameters.max, parameters.min, parameters.heartbeat); // If price is in ETH, then convert price into USD. if (parameters.inETH) { uint256 _ethToUsd = _getPriceInUSD(WETH, getAssetSettings[WETH]); price = price.mulWadDown(_ethToUsd); } return price; } /** * @notice Attempted an operation to price an asset that under its minimum valid price. * @param asset address of the asset that is under its minimum valid price * @param price price of the asset * @param minPrice minimum valid price of the asset */ error PriceRouter__AssetBelowMinPrice(address asset, uint256 price, uint256 minPrice); /** * @notice Attempted an operation to price an asset that under its maximum valid price. * @param asset address of the asset that is under its maximum valid price * @param price price of the asset * @param maxPrice maximum valid price of the asset */ error PriceRouter__AssetAboveMaxPrice(address asset, uint256 price, uint256 maxPrice); /** * @notice Attempted to fetch a price for an asset that has not been updated in too long. * @param asset address of the asset thats price is stale * @param timeSinceLastUpdate seconds since the last price update * @param heartbeat maximum allowed time between price updates */ error PriceRouter__StalePrice(address asset, uint256 timeSinceLastUpdate, uint256 heartbeat); /** * @notice helper function to validate a price feed is safe to use. * @param asset ERC20 asset price feed data is for. * @param value the price value the price feed gave. * @param timestamp the last timestamp the price feed was updated. * @param max the upper price bound * @param min the lower price bound * @param heartbeat the max amount of time between price updates */ function _checkPriceFeed( address asset, uint256 value, uint256 timestamp, uint144 max, uint88 min, uint24 heartbeat ) internal view { if (value < min) revert PriceRouter__AssetBelowMinPrice(address(asset), value, min); if (value > max) revert PriceRouter__AssetAboveMaxPrice(address(asset), value, max); uint256 timeSinceLastUpdate = block.timestamp - timestamp; if (timeSinceLastUpdate > heartbeat) revert PriceRouter__StalePrice(address(asset), timeSinceLastUpdate, heartbeat); } // =========================================== TWAP PRICE DERIVATIVE =========================================== /** * @notice Stores data for Twap derivative assets. * @param secondsAgo the twap duration * @param baseDecimals the base assets decimals * @param quoteDecimals the quote assets decimals * @param quoteToken the asset the twap quotes in */ struct TwapDerivativeStorage { uint32 secondsAgo; uint8 baseDecimals; uint8 quoteDecimals; ERC20 quoteToken; } /** * @notice Tried setting up a Twap for an asset where the underlying pools does not use the asset. */ error PriceRouter__TwapAssetNotInPool(); /** * @notice Provided secondsAgo does not meet minimum, */ error PriceRouter__SecondsAgoDoesNotMeetMinimum(); /** * @notice Returns Twap Derivative Storage */ mapping(ERC20 => TwapDerivativeStorage) public getTwapDerivativeStorage; /** * @notice The smallest possible TWAP that can be used. */ uint32 public constant MINIMUM_SECONDS_AGO = 900; /** * @notice Setup function for pricing Twap derivative assets. * @dev Make sure that TWAP assets have sufficient observations, and increase them if not before adding. * @dev _source The address of the Uniswap V3 pool. * @dev _storage A TwapDerivativeStorage value defining valid prices. */ function _setupPriceForTwapDerivative(ERC20 _asset, address _source, bytes memory _storage) internal { TwapDerivativeStorage memory parameters = abi.decode(_storage, (TwapDerivativeStorage)); // Verify seconds ago is reasonable. if (parameters.secondsAgo < MINIMUM_SECONDS_AGO) revert PriceRouter__SecondsAgoDoesNotMeetMinimum(); UniswapV3Pool pool = UniswapV3Pool(_source); ERC20 token0 = ERC20(pool.token0()); ERC20 token1 = ERC20(pool.token1()); if (token0 == _asset) { parameters.baseDecimals = _asset.decimals(); parameters.quoteDecimals = token1.decimals(); parameters.quoteToken = token1; } else if (token1 == _asset) { parameters.baseDecimals = _asset.decimals(); parameters.quoteDecimals = token0.decimals(); parameters.quoteToken = token0; } else revert PriceRouter__TwapAssetNotInPool(); getTwapDerivativeStorage[_asset] = parameters; } /** * @notice Get the price of a Twap derivative in terms of USD. */ function _getPriceForTwapDerivative(ERC20 asset, address _source) internal view returns (uint256) { TwapDerivativeStorage memory parameters = getTwapDerivativeStorage[asset]; (int24 arithmeticMeanTick, ) = OracleLibrary.consult(_source, parameters.secondsAgo); // Get the amount of quote token each base token is worth. uint256 quoteAmount = OracleLibrary.getQuoteAtTick( arithmeticMeanTick, uint128(10 ** parameters.baseDecimals), address(asset), address(parameters.quoteToken) ); uint256 quotePrice = _getPriceInUSD(parameters.quoteToken, getAssetSettings[parameters.quoteToken]); return quoteAmount.mulDivDown(quotePrice, 10 ** parameters.quoteDecimals); } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; /** * @notice A library to extend the uint32 array data type. */ library Uint32Array { // =========================================== ADDRESS STORAGE =========================================== /** * @notice Add an uint32 to the array at a given index. * @param array uint32 array to add the uint32 to * @param index index to add the uint32 at * @param value uint32 to add to the array */ function add(uint32[] storage array, uint32 index, uint32 value) internal { uint256 len = array.length; if (len > 0) { array.push(array[len - 1]); for (uint256 i = len - 1; i > index; i--) array[i] = array[i - 1]; array[index] = value; } else { array.push(value); } } /** * @notice Remove a uint32 from the array at a given index. * @param array uint32 array to remove the uint32 from * @param index index to remove the uint32 at */ function remove(uint32[] storage array, uint32 index) internal { uint256 len = array.length; require(index < len, "Index out of bounds"); for (uint256 i = index; i < len - 1; i++) array[i] = array[i + 1]; array.pop(); } /** * @notice Check whether an array contains an uint32. * @param array uint32 array to check * @param value uint32 to check for */ function contains(uint32[] storage array, uint32 value) internal view returns (bool) { for (uint256 i; i < array.length; i++) if (value == array[i]) return true; return false; } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import { Math } from "src/utils/Math.sol"; import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol"; import { ERC20 } from "@solmate/tokens/ERC20.sol"; import { Registry } from "src/Registry.sol"; import { Cellar } from "src/base/Cellar.sol"; import { PriceRouter } from "src/modules/price-router/PriceRouter.sol"; /** * @title Base Adaptor * @notice Base contract all adaptors must inherit from. * @dev Allows Cellars to interact with arbritrary DeFi assets and protocols. * @author crispymangoes */ abstract contract BaseAdaptor { using SafeTransferLib for ERC20; using Math for uint256; /** * @notice Attempted to specify an external receiver during a Cellar `callOnAdaptor` call. */ error BaseAdaptor__ExternalReceiverBlocked(); /** * @notice Attempted to deposit to a position where user deposits were not allowed. */ error BaseAdaptor__UserDepositsNotAllowed(); /** * @notice Attempted to withdraw from a position where user withdraws were not allowed. */ error BaseAdaptor__UserWithdrawsNotAllowed(); /** * @notice Attempted swap has bad slippage. */ error BaseAdaptor__Slippage(); /** * @notice Attempted swap used unsupported output asset. */ error BaseAdaptor__PricingNotSupported(address asset); /** * @notice Attempted to set a constructor minimum health factor to a value * below `MINIMUM_CONSTRUCTOR_HEALTH_FACTOR()`. */ error BaseAdaptor__ConstructorHealthFactorTooLow(); //============================================ Global Functions =========================================== /** * @dev Identifier unique to this adaptor for a shared registry. * Normally the identifier would just be the address of this contract, but this * Identifier is needed during Cellar Delegate Call Operations, so getting the address * of the adaptor is more difficult. */ function identifier() public pure virtual returns (bytes32) { return keccak256(abi.encode("Base Adaptor V 0.0")); } function SWAP_ROUTER_REGISTRY_SLOT() internal pure returns (uint256) { return 1; } function PRICE_ROUTER_REGISTRY_SLOT() internal pure returns (uint256) { return 2; } /** * @notice Max possible slippage when making a swap router swap. */ function slippage() public pure returns (uint32) { return 0.9e4; } /** * @notice The default minimum constructor health factor. * @dev Adaptors can choose to override this if they need a different value. */ function MINIMUM_CONSTRUCTOR_HEALTH_FACTOR() internal pure virtual returns (uint256) { return 1.01e18; } //============================================ Implement Base Functions =========================================== //==================== Base Function Specification ==================== // Base functions are functions designed to help the Cellar interact with // an adaptor position, strategists are not intended to use these functions. // Base functions MUST be implemented in adaptor contracts, even if that is just // adding a revert statement to make them uncallable by normal user operations. // // All view Base functions will be called used normal staticcall. // All mutative Base functions will be called using delegatecall. //===================================================================== /** * @notice Function Cellars call to deposit users funds into holding position. * @param assets the amount of assets to deposit * @param adaptorData data needed to deposit into a position * @param configurationData data settable when strategists add positions to their Cellar * Allows strategist to control how the adaptor interacts with the position */ function deposit(uint256 assets, bytes memory adaptorData, bytes memory configurationData) public virtual; /** * @notice Function Cellars call to withdraw funds from positions to send to users. * @param receiver the address that should receive withdrawn funds * @param adaptorData data needed to withdraw from a position * @param configurationData data settable when strategists add positions to their Cellar * Allows strategist to control how the adaptor interacts with the position */ function withdraw( uint256 assets, address receiver, bytes memory adaptorData, bytes memory configurationData ) public virtual; /** * @notice Function Cellars use to determine `assetOf` balance of an adaptor position. * @param adaptorData data needed to interact with the position * @return balance of the position in terms of `assetOf` */ function balanceOf(bytes memory adaptorData) public view virtual returns (uint256); /** * @notice Functions Cellars use to determine the withdrawable balance from an adaptor position. * @dev Debt positions MUST return 0 for their `withdrawableFrom` * @notice accepts adaptorData and configurationData * @return withdrawable balance of the position in terms of `assetOf` */ function withdrawableFrom(bytes memory, bytes memory) public view virtual returns (uint256); /** * @notice Function Cellars use to determine the underlying ERC20 asset of a position. * @param adaptorData data needed to withdraw from a position * @return the underlying ERC20 asset of a position */ function assetOf(bytes memory adaptorData) public view virtual returns (ERC20); /** * @notice When positions are added to the Registry, this function can be used in order to figure out * what assets this adaptor needs to price, and confirm pricing is properly setup. */ function assetsUsed(bytes memory adaptorData) public view virtual returns (ERC20[] memory assets) { assets = new ERC20[](1); assets[0] = assetOf(adaptorData); } /** * @notice Functions Registry/Cellars use to determine if this adaptor reports debt values. * @dev returns true if this adaptor reports debt values. */ function isDebt() public view virtual returns (bool); //============================================ Strategist Functions =========================================== //==================== Strategist Function Specification ==================== // Strategist functions are only callable by strategists through the Cellars // `callOnAdaptor` function. A cellar will never call any of these functions, // when a normal user interacts with a cellar(depositing/withdrawing) // // All strategist functions will be called using delegatecall. // Strategist functions are intentionally "blind" to what positions the cellar // is currently holding. This allows strategists to enter temporary positions // while rebalancing. // To mitigate strategist from abusing this and moving funds in untracked // positions, the cellar will enforce a Total Value Locked check that // insures TVL has not deviated too much from `callOnAdaptor`. //=========================================================================== //============================================ Helper Functions =========================================== /** * @notice Helper function that allows adaptor calls to use the max available of an ERC20 asset * by passing in type(uint256).max * @param token the ERC20 asset to work with * @param amount when `type(uint256).max` is used, this function returns `token`s `balanceOf` * otherwise this function returns amount. */ function _maxAvailable(ERC20 token, uint256 amount) internal view virtual returns (uint256) { if (amount == type(uint256).max) return token.balanceOf(address(this)); else return amount; } /** * @notice Helper function that checks if `spender` has any more approval for `asset`, and if so revokes it. */ function _revokeExternalApproval(ERC20 asset, address spender) internal { if (asset.allowance(address(this), spender) > 0) asset.safeApprove(spender, 0); } /** * @notice Helper function that validates external receivers are allowed. */ function _externalReceiverCheck(address receiver) internal view { if (receiver != address(this) && Cellar(address(this)).blockExternalReceiver()) revert BaseAdaptor__ExternalReceiverBlocked(); } /** * @notice Helper function that validates external receivers are allowed. */ function _verifyConstructorMinimumHealthFactor(uint256 minimumHealthFactor) internal pure { if (minimumHealthFactor < MINIMUM_CONSTRUCTOR_HEALTH_FACTOR()) revert BaseAdaptor__ConstructorHealthFactorTooLow(); } /** * @notice Allows strategists to zero out an approval for a given `asset`. * @param asset the ERC20 asset to revoke `spender`s approval for * @param spender the address to revoke approval for */ function revokeApproval(ERC20 asset, address spender) public { asset.safeApprove(spender, 0); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.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 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol) abstract contract Auth { event OwnershipTransferred(address indexed user, address indexed newOwner); event AuthorityUpdated(address indexed user, Authority indexed newAuthority); address public owner; Authority public authority; constructor(address _owner, Authority _authority) { owner = _owner; authority = _authority; emit OwnershipTransferred(msg.sender, _owner); emit AuthorityUpdated(msg.sender, _authority); } modifier requiresAuth() virtual { require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED"); _; } function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) { Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas. // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be // aware that this makes protected functions uncallable even to the owner if the authority is out of order. return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner; } function setAuthority(Authority newAuthority) public virtual { // We check if the caller is the owner first because we want to ensure they can // always swap out the authority even if it's reverting or using up a lot of gas. require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig)); authority = newAuthority; emit AuthorityUpdated(msg.sender, newAuthority); } function transferOwnership(address newOwner) public virtual requiresAuth { owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } } /// @notice A generic interface for a contract which provides authorization data to an Auth instance. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol) interface Authority { function canCall( address user, address target, bytes4 functionSig ) external view returns (bool); }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import { Registry, ERC20, Math, SafeTransferLib } from "src/base/Cellar.sol"; import { IFlashLoanRecipient, IERC20 } from "@balancer/interfaces/contracts/vault/IFlashLoanRecipient.sol"; import { CellarWithOracle } from "src/base/permutations/CellarWithOracle.sol"; import { ERC4626SharePriceOracle } from "src/base/ERC4626SharePriceOracle.sol"; contract CellarWithOracleWithBalancerFlashLoans is CellarWithOracle, IFlashLoanRecipient { using Math for uint256; using SafeTransferLib for ERC20; /** * @notice The Balancer Vault contract on current network. * @dev For mainnet use 0xBA12222222228d8Ba445958a75a0704d566BF2C8. */ address internal immutable balancerVault; constructor( address _owner, Registry _registry, ERC20 _asset, string memory _name, string memory _symbol, uint32 _holdingPosition, bytes memory _holdingPositionConfig, uint256 _initialDeposit, uint64 _strategistPlatformCut, uint192 _shareSupplyCap, address _balancerVault ) CellarWithOracle( _owner, _registry, _asset, _name, _symbol, _holdingPosition, _holdingPositionConfig, _initialDeposit, _strategistPlatformCut, _shareSupplyCap ) { balancerVault = _balancerVault; } // ========================================= Balancer Flash Loan Support ========================================= /** * @notice External contract attempted to initiate a flash loan. */ error Cellar__ExternalInitiator(); /** * @notice receiveFlashLoan was not called by Balancer Vault. */ error Cellar__CallerNotBalancerVault(); /** * @notice Allows strategist to utilize balancer flashloans while rebalancing the cellar. * @dev Balancer does not provide an initiator, so instead insure we are in the `callOnAdaptor` context * by reverting if `blockExternalReceiver` is false. */ function receiveFlashLoan( IERC20[] calldata tokens, uint256[] calldata amounts, uint256[] calldata feeAmounts, bytes calldata userData ) external { if (msg.sender != balancerVault) revert Cellar__CallerNotBalancerVault(); if (!blockExternalReceiver) revert Cellar__ExternalInitiator(); AdaptorCall[] memory data = abi.decode(userData, (AdaptorCall[])); // Run all adaptor calls. _makeAdaptorCalls(data); // Approve pool to repay all debt. for (uint256 i = 0; i < amounts.length; ++i) { ERC20(address(tokens[i])).safeTransfer(balancerVault, (amounts[i] + feeAmounts[i])); } } }
// 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)) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol"; interface IChainlinkAggregator is AggregatorV2V3Interface { function maxAnswer() external view returns (int192); function minAnswer() external view returns (int192); function aggregator() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.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: Apache-2.0 pragma solidity 0.8.21; import { ERC20 } from "@solmate/tokens/ERC20.sol"; import { PriceRouter } from "src/modules/price-router/PriceRouter.sol"; import { Math } from "src/utils/Math.sol"; /** * @title Sommelier Price Router Extension abstract contract. * @notice Provides shared logic between Extensions. * @author crispymangoes */ abstract contract Extension { /** * @notice Attempted to call a function only callable by the price router. */ error Extension__OnlyPriceRouter(); /** * @notice Prevents non price router contracts from calling a function. */ modifier onlyPriceRouter() { if (msg.sender != address(priceRouter)) revert Extension__OnlyPriceRouter(); _; } /** * @notice The Sommelier PriceRouter contract. */ PriceRouter public immutable priceRouter; constructor(PriceRouter _priceRouter) { priceRouter = _priceRouter; } /** * @notice Setup function is called when an asset is added/edited. */ function setupSource(ERC20 asset, bytes memory sourceData) external virtual; /** * @notice Returns the price of an asset in USD. */ function getPriceInUSD(ERC20 asset) external view virtual returns (uint256); }
pragma solidity ^0.8.10; interface UniswapV3Pool { event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); event Initialize(uint160 sqrtPriceX96, int24 tick); event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1); function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); function factory() external view returns (address); function fee() external view returns (uint24); function feeGrowthGlobal0X128() external view returns (uint256); function feeGrowthGlobal1X128() external view returns (uint256); function flash(address recipient, uint256 amount0, uint256 amount1, bytes memory data) external; function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; function initialize(uint160 sqrtPriceX96) external; function liquidity() external view returns (uint128); function maxLiquidityPerTick() external view returns (uint128); function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes memory data ) external returns (uint256 amount0, uint256 amount1); function observations( uint256 ) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); function observe( uint32[] memory secondsAgos ) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); function positions( bytes32 ) external view returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); function protocolFees() external view returns (uint128 token0, uint128 token1); function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); function snapshotCumulativesInside( int24 tickLower, int24 tickUpper ) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside); function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes memory data ) external returns (int256 amount0, int256 amount1); function tickBitmap(int16) external view returns (uint256); function tickSpacing() external view returns (int24); function ticks( int24 ) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); function token0() external view returns (address); function token1() external view returns (address); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.9.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool /// @param pool Address of the pool that we want to observe /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp function consult(address pool, uint32 secondsAgo) internal view returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity) { require(secondsAgo != 0, 'BP'); uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = secondsAgo; secondsAgos[1] = 0; (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = IUniswapV3Pool(pool) .observe(secondsAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0]; arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo))); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--; // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128 uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max; harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32)); } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation /// @param pool Address of Uniswap V3 pool that we want to observe /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) { (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); require(observationCardinality > 0, 'NI'); (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations( (observationIndex + 1) % observationCardinality ); // The next index might not be initialized if the cardinality is in the process of increasing // In this case the oldest observation is always in index 0 if (!initialized) { (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0); } unchecked { secondsAgo = uint32(block.timestamp) - observationTimestamp; } } /// @notice Given a pool, it returns the tick value as of the start of the current block /// @param pool Address of Uniswap V3 pool /// @return The tick that the pool was in at the start of the current block function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) { (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); // 2 observations are needed to reliably calculate the block starting tick require(observationCardinality > 1, 'NEO'); // If the latest observation occurred in the past, then no tick-changing trades have happened in this block // therefore the tick in `slot0` is the same as at the beginning of the current block. // We don't need to check if this observation is initialized - it is guaranteed to be. ( uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) = IUniswapV3Pool(pool).observations(observationIndex); if (observationTimestamp != uint32(block.timestamp)) { return (tick, IUniswapV3Pool(pool).liquidity()); } uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality; ( uint32 prevObservationTimestamp, int56 prevTickCumulative, uint160 prevSecondsPerLiquidityCumulativeX128, bool prevInitialized ) = IUniswapV3Pool(pool).observations(prevIndex); require(prevInitialized, 'ONI'); uint32 delta = observationTimestamp - prevObservationTimestamp; tick = int24((tickCumulative - int56(uint56(prevTickCumulative))) / int56(uint56(delta))); uint128 liquidity = uint128( (uint192(delta) * type(uint160).max) / (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32) ); return (tick, liquidity); } /// @notice Information for calculating a weighted arithmetic mean tick struct WeightedTickData { int24 tick; uint128 weight; } /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick /// @param weightedTickData An array of ticks and weights /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not, /// extreme care must be taken to ensure that ticks are comparable (including decimal differences). /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price. function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData) internal pure returns (int24 weightedArithmeticMeanTick) { // Accumulates the sum of products between each tick and its weight int256 numerator; // Accumulates the sum of the weights uint256 denominator; // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic for (uint256 i; i < weightedTickData.length; i++) { numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight)); denominator += weightedTickData[i].weight; } weightedArithmeticMeanTick = int24(numerator / int256(denominator)); // Always round to negative infinity if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--; } /// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last /// @dev Useful for calculating relative prices along routes. /// @dev There must be one tick for each pairwise set of tokens. /// @param tokens The token contract addresses /// @param ticks The ticks, representing the price of each token pair in `tokens` /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens` function getChainedPrice(address[] memory tokens, int24[] memory ticks) internal pure returns (int256 syntheticTick) { require(tokens.length - 1 == ticks.length, 'DL'); for (uint256 i = 1; i <= ticks.length; i++) { // check the tokens for address sort order, then accumulate the // ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out" tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1]; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); }
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.7.0 <0.9.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "../solidity-utils/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import { Cellar, Registry, ERC20, Math } from "src/base/Cellar.sol"; import { ERC4626SharePriceOracle } from "src/base/ERC4626SharePriceOracle.sol"; contract CellarWithOracle is Cellar { using Math for uint256; constructor( address _owner, Registry _registry, ERC20 _asset, string memory _name, string memory _symbol, uint32 _holdingPosition, bytes memory _holdingPositionConfig, uint256 _initialDeposit, uint64 _strategistPlatformCut, uint192 _shareSupplyCap ) Cellar( _owner, _registry, _asset, _name, _symbol, _holdingPosition, _holdingPositionConfig, _initialDeposit, _strategistPlatformCut, _shareSupplyCap ) {} /** * @notice The ERC4626 Share Price Oracle this Cellar uses to calculate its totalAssets, * during user entry/exits. */ ERC4626SharePriceOracle public sharePriceOracle; /** * @notice Emitted when Share Price Oracle is changed. */ event SharePriceOracleUpdated(address newOracle); /** * @notice The decimals the Cellar is expecting the oracle to have. */ uint8 internal constant ORACLE_DECIMALS = 18; /** * @notice Some failure occurred while trying to setup/use the oracle. */ error Cellar__OracleFailure(); /** * @notice Change the share price oracle this Cellar uses for share price calculations. * @dev Only callable through Sommelier Governance. * @dev Trying to set the share price oracle to the zero address will revert here. * @dev Callable by Sommelier Governance. */ function setSharePriceOracle(uint256 _registryId, ERC4626SharePriceOracle _sharePriceOracle) external requiresAuth { _checkRegistryAddressAgainstExpected(_registryId, address(_sharePriceOracle)); if (_sharePriceOracle.decimals() != ORACLE_DECIMALS || address(_sharePriceOracle.target()) != address(this)) revert Cellar__OracleFailure(); sharePriceOracle = _sharePriceOracle; emit SharePriceOracleUpdated(address(_sharePriceOracle)); } /** * @notice Estimate totalAssets be querying oracle to get latest answer, and time weighted average answer. * @dev If useUpper is true, use larger of the 2 to maximize share price * else use smaller of the 2 to minimize share price * @dev _totalAssets calculation is dependent on the Cellar having the same amount of decimals as the underlying asset. */ function _getTotalAssetsAndTotalSupply( bool useUpper ) internal view override returns (uint256 _totalAssets, uint256 _totalSupply) { ERC4626SharePriceOracle _sharePriceOracle = sharePriceOracle; // Check if sharePriceOracle is set. if (address(_sharePriceOracle) != address(0)) { // Consult the oracle. (uint256 latestAnswer, uint256 timeWeightedAverageAnswer, bool isNotSafeToUse) = _sharePriceOracle .getLatest(); if (isNotSafeToUse) revert Cellar__OracleFailure(); else { uint256 sharePrice; if (useUpper) sharePrice = latestAnswer > timeWeightedAverageAnswer ? latestAnswer : timeWeightedAverageAnswer; else sharePrice = latestAnswer < timeWeightedAverageAnswer ? latestAnswer : timeWeightedAverageAnswer; // Convert share price to totalAssets. _totalSupply = totalSupply; _totalAssets = sharePrice.mulDivDown(_totalSupply, 10 ** ORACLE_DECIMALS); } } else revert Cellar__OracleFailure(); } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; import { ERC4626 } from "@solmate/mixins/ERC4626.sol"; import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol"; import { ERC20 } from "@solmate/tokens/ERC20.sol"; import { Math } from "src/utils/Math.sol"; import { Owned } from "@solmate/auth/Owned.sol"; import { AutomationCompatibleInterface } from "@chainlink/contracts/src/v0.8/interfaces/AutomationCompatibleInterface.sol"; import { IRegistrar } from "src/interfaces/external/Chainlink/IRegistrar.sol"; import { IRegistry } from "src/interfaces/external/Chainlink/IRegistry.sol"; import { IChainlinkAggregator } from "src/interfaces/external/IChainlinkAggregator.sol"; contract ERC4626SharePriceOracle is AutomationCompatibleInterface { using Math for uint256; using SafeTransferLib for ERC20; // ========================================= STRUCTS ========================================= struct Observation { uint64 timestamp; uint192 cumulative; } /** * @notice Use a struct for constructor args so we do not encounter stack too deep errors. */ struct ConstructorArgs { ERC4626 _target; uint64 _heartbeat; uint64 _deviationTrigger; uint64 _gracePeriod; uint16 _observationsToUse; address _automationRegistry; address _automationRegistrar; address _automationAdmin; address _link; uint216 _startingAnswer; uint256 _allowedAnswerChangeLower; uint256 _allowedAnswerChangeUpper; address _sequencerUptimeFeed; uint64 _sequencerGracePeriod; } // ========================================= CONSTANTS ========================================= /** * @notice Gas Limit to use for Upkeep created in `initialize`. * @dev Should be fairly constant between networks, but 50_000 is a safe limit in * most situations. */ uint32 public constant UPKEEP_GAS_LIMIT = 50_000; /** * @notice Decimals used to scale share price for internal calculations. */ uint8 public constant decimals = 18; // ========================================= GLOBAL STATE ========================================= /** * @notice The latest stored onchain answer. */ uint216 public answer; /** * @notice Stores the index of observations with the pending Observation. */ uint16 public currentIndex; /** * @notice The length of the observations array. * @dev `observations` will never change its length once set in the constructor. * By saving this value here, we can take advantage of variable packing to make reads cheaper. * @dev This is not immutable to make it easier in the future to create oracles that can expand their observations. */ uint16 public observationsLength; /** * @notice Triggered when answer provided by Chainlink Automation is extreme. * @dev true: No further upkeeps are allowed, `getLatest` and `getLatestAnswer` will return true error bools. * false: Continue as normal. */ bool public killSwitch; /** * @notice Stores the observations this contract uses to derive a * time weighted average answer. */ Observation[] public observations; /** * @notice The Automation V2 Forwarder address for this contract. */ address public automationForwarder; /** * @notice keccak256 hash of the parameters used to create this upkeep. * @dev Only set if `initialize` leads to a pending upkeep. */ bytes32 public pendingUpkeepParamHash; //============================== ERRORS =============================== error ERC4626SharePriceOracle__OnlyCallableByAutomationForwarder(); error ERC4626SharePriceOracle__StalePerformData(); error ERC4626SharePriceOracle__CumulativeTooLarge(); error ERC4626SharePriceOracle__NoUpkeepConditionMet(); error ERC4626SharePriceOracle__SharePriceTooLarge(); error ERC4626SharePriceOracle__FuturePerformData(); error ERC4626SharePriceOracle__ContractKillSwitch(); error ERC4626SharePriceOracle__AlreadyInitialized(); error ERC4626SharePriceOracle__ParamHashDiffers(); error ERC4626SharePriceOracle__NoPendingUpkeepToHandle(); //============================== EVENTS =============================== /** * @notice Emitted when performUpkeep is ran. * @param timeUpdated the time the answer was updated on chain * @param timeAnswerCalculated the time the answer was calculated in checkUpkeep * @param latestAnswer the new answer * @param timeWeightedAverageAnswer the new time weighted average answer * @param isNotSafeToUse bool * if true: `timeWeightedAverageAnswer` is illogical, use `latestAnswer` * if false: use `timeWeightedAverageAnswer` */ event OracleUpdated( uint256 timeUpdated, uint256 timeAnswerCalculated, uint256 latestAnswer, uint256 timeWeightedAverageAnswer, bool isNotSafeToUse ); /** * @notice Emitted when the oracles kill switch is activated. * @dev If this happens, then the proposed performData lead to extremely volatile share price, * so we need to investigate why that happened, mitigate it, then launch a new share price oracle. */ event KillSwitchActivated(uint256 reportedAnswer, uint256 minAnswer, uint256 maxAnswer); /** * @notice Emitted when the upkeep is registered. */ event UpkeepRegistered(uint256 upkeepId, address forwarder); /** * @notice Emitted when a upkeep registration is left pending. */ event UpkeepPending(bytes32 upkeepParamHash); //============================== IMMUTABLES =============================== /** * @notice Determines the minimum time for each observation, and is used to determine if an * answer is stale. */ uint64 public immutable heartbeat; /** * @notice Used to enforce that the summation of each observations delay used in * a time weighed average calculation is less than the gracePeriod. * @dev Example: Using a 3 day TWAA with 1 hour grace period. * When calculating the TWAA, the total time delta for completed observations must be greater than 3 days but less than * 3 days + 1hr. So one observation could be delayed 1 hr, or two observations could be * delayed 30 min each. */ uint64 public immutable gracePeriod; /** * @notice Number between 0 -> 10_000 that determines how far off the last saved answer * can deviate from the current answer. * @dev This value should be reflective of the vaults expected maximum percent share * price change during a heartbeat duration. * @dev * -1_000 == 10% * -100 == 1% * -10 == 0.1% * -1 == 0.01% or 1 bps */ uint64 public immutable deviationTrigger; /** * @notice One share of target vault. */ uint256 public immutable ONE_SHARE; /** * @notice The admin address for the Automation Upkeep. */ address public immutable automationAdmin; /** * @notice Chainlink's Automation Registry contract address. * @notice For mainnet use 0x6593c7De001fC8542bB1703532EE1E5aA0D458fD. */ address public immutable automationRegistry; /** * @notice Chainlink's Automation Registrar contract address. * @notice For mainnet use 0x6B0B234fB2f380309D47A7E9391E29E9a179395a. */ address public immutable automationRegistrar; /** * @notice Link Token. * @notice For mainnet use 0x514910771AF9Ca656af840dff83E8264EcF986CA. */ ERC20 public immutable link; /** * @notice ERC4626 target vault this contract is an oracle for. */ ERC4626 public immutable target; /** * @notice Target vault decimals. */ uint8 public immutable targetDecimals; /** * @notice Multiplier with 4 decimals that determines the acceptable lower band * for a performUpkeep answer. */ uint256 public immutable allowedAnswerChangeLower; /** * @notice Multiplier with 4 decimals that determines the acceptable upper band * for a performUpkeep answer. */ uint256 public immutable allowedAnswerChangeUpper; /** * @notice Address for the networks sequencer uptime feed. * @dev For oracles that do not rely on a sequencer being up, use address(0). */ IChainlinkAggregator internal immutable sequencerUptimeFeed; /** * @notice The grace period to enforce after a sequencer comes back online. * @dev Calls to `getLatest` and `getLatestAnswer` will return a true for * `isNotSafeToUse` if the sequencer is down, or if the time since the * sequencer went back online is less than `sequencerGracePeriod`. */ uint64 public immutable sequencerGracePeriod; /** * @notice TWAA Minimum Duration = `_observationsToUse` * `_heartbeat`. * @notice TWAA Maximum Duration = `_observationsToUse` * `_heartbeat` + `gracePeriod` + `_heartbeat`. * @notice TWAA calculations will use the current pending observation, and then `_observationsToUse` observations. */ constructor(ConstructorArgs memory args) { target = args._target; targetDecimals = target.decimals(); ONE_SHARE = 10 ** targetDecimals; heartbeat = args._heartbeat; deviationTrigger = args._deviationTrigger; gracePeriod = args._gracePeriod; // Add 1 to observations to use. args._observationsToUse = args._observationsToUse + 1; observationsLength = args._observationsToUse; // Grow Observations array to required length, and fill it with observations that use 1 for timestamp and cumulative. // That way the initial upkeeps won't need to change state from 0 which is more expensive. for (uint256 i; i < args._observationsToUse; ++i) observations.push(Observation({ timestamp: 1, cumulative: 1 })); // Set to args._startingAnswer so slot is dirty for first upkeep, and does not trigger kill switch. answer = args._startingAnswer; if (args._allowedAnswerChangeLower > 1e4) revert("Illogical Lower"); allowedAnswerChangeLower = args._allowedAnswerChangeLower; if (args._allowedAnswerChangeUpper < 1e4) revert("Illogical Upper"); allowedAnswerChangeUpper = args._allowedAnswerChangeUpper; automationRegistry = args._automationRegistry; automationRegistrar = args._automationRegistrar; automationAdmin = args._automationAdmin; link = ERC20(args._link); sequencerUptimeFeed = IChainlinkAggregator(args._sequencerUptimeFeed); sequencerGracePeriod = args._sequencerGracePeriod; } //============================== INITIALIZATION =============================== /** * @notice Should be called after contract creation. * @dev Creates a Chainlink Automation Upkeep, and set the `automationForwarder` address. */ function initialize(uint96 initialUpkeepFunds) external { // This function is only callable once. if (automationForwarder != address(0) || pendingUpkeepParamHash != bytes32(0)) revert ERC4626SharePriceOracle__AlreadyInitialized(); link.safeTransferFrom(msg.sender, address(this), initialUpkeepFunds); // Create the upkeep. IRegistrar registrar = IRegistrar(automationRegistrar); IRegistry registry = IRegistry(automationRegistry); IRegistrar.RegistrationParams memory params = IRegistrar.RegistrationParams({ name: string.concat(target.name(), " Share Price Oracle"), encryptedEmail: hex"", upkeepContract: address(this), gasLimit: UPKEEP_GAS_LIMIT, adminAddress: automationAdmin, triggerType: 0, checkData: hex"", triggerConfig: hex"", offchainConfig: hex"", amount: initialUpkeepFunds }); link.safeApprove(automationRegistrar, initialUpkeepFunds); uint256 upkeepID = registrar.registerUpkeep(params); if (upkeepID > 0) { // Upkeep was successfully registered. address forwarder = registry.getForwarder(upkeepID); automationForwarder = forwarder; emit UpkeepRegistered(upkeepID, forwarder); } else { // Upkeep is pending. bytes32 paramHash = keccak256( abi.encode( params.upkeepContract, params.gasLimit, params.adminAddress, params.triggerType, params.checkData, params.offchainConfig ) ); pendingUpkeepParamHash = paramHash; emit UpkeepPending(paramHash); } } /** * @notice Finish setting forwarder address if `initialize` did not get an auto-approved upkeep. */ function handlePendingUpkeep(uint256 _upkeepId) external { if (pendingUpkeepParamHash == bytes32(0) || automationForwarder != address(0)) revert ERC4626SharePriceOracle__NoPendingUpkeepToHandle(); IRegistry registry = IRegistry(automationRegistry); IRegistry.UpkeepInfo memory upkeepInfo = registry.getUpkeep(_upkeepId); // Build the param hash using upkeepInfo. // The upkeep id has 16 bytes of entropy, that need to be shifted out(16*8=128). // Then take the resulting number and only take the last byte of it to get the trigger type. uint8 triggerType = uint8(_upkeepId >> 128); bytes32 proposedParamHash = keccak256( abi.encode( upkeepInfo.target, upkeepInfo.executeGas, upkeepInfo.admin, triggerType, upkeepInfo.checkData, upkeepInfo.offchainConfig ) ); if (pendingUpkeepParamHash != proposedParamHash) revert ERC4626SharePriceOracle__ParamHashDiffers(); // Hashes match, so finish initialization. address forwarder = registry.getForwarder(_upkeepId); automationForwarder = forwarder; emit UpkeepRegistered(_upkeepId, forwarder); } //============================== CHAINLINK AUTOMATION =============================== /** * @notice Leverages Automation V2 secure offchain computation to run expensive share price calculations offchain, * then inject them onchain using `performUpkeep`. */ function checkUpkeep(bytes calldata) external view returns (bool upkeepNeeded, bytes memory performData) { // Get target share price. uint216 sharePrice = _getTargetSharePrice(); // Read state from one slot. uint256 _answer = answer; uint16 _currentIndex = currentIndex; uint16 _observationsLength = observationsLength; bool _killSwitch = killSwitch; if (!_killSwitch) { // See if we need to update because answer is stale or outside deviation. // Time since answer was last updated. uint256 timeDeltaCurrentAnswer = block.timestamp - observations[_currentIndex].timestamp; uint256 timeDeltaSincePreviousObservation = block.timestamp - observations[_getPreviousIndex(_currentIndex, _observationsLength)].timestamp; uint64 _heartbeat = heartbeat; if ( timeDeltaCurrentAnswer >= _heartbeat || timeDeltaSincePreviousObservation >= _heartbeat || sharePrice > _answer.mulDivDown(1e4 + deviationTrigger, 1e4) || sharePrice < _answer.mulDivDown(1e4 - deviationTrigger, 1e4) ) { // We need to update answer. upkeepNeeded = true; performData = abi.encode(sharePrice, uint64(block.timestamp)); } } // else no upkeep is needed } /** * @notice Save answer on chain, and update observations if needed. */ function performUpkeep(bytes calldata performData) external { if (msg.sender != automationForwarder) revert ERC4626SharePriceOracle__OnlyCallableByAutomationForwarder(); (uint216 sharePrice, uint64 currentTime) = abi.decode(performData, (uint216, uint64)); // Verify atleast one of the upkeep conditions was met. bool upkeepConditionMet; // Read state from one slot. uint256 _answer = answer; uint16 _currentIndex = currentIndex; uint16 _observationsLength = observationsLength; bool _killSwitch = killSwitch; if (_killSwitch) revert ERC4626SharePriceOracle__ContractKillSwitch(); // See if kill switch should be activated based on change between answers. if (_checkIfKillSwitchShouldBeTriggered(sharePrice, _answer)) return; // See if we are upkeeping because of deviation. if ( sharePrice > uint256(_answer).mulDivDown(1e4 + deviationTrigger, 1e4) || sharePrice < uint256(_answer).mulDivDown(1e4 - deviationTrigger, 1e4) ) upkeepConditionMet = true; // Update answer. answer = sharePrice; // Update current observation. Observation storage currentObservation = observations[_currentIndex]; // Make sure time is larger than previous time. if (currentTime <= currentObservation.timestamp) revert ERC4626SharePriceOracle__StalePerformData(); // Make sure time is not in the future. if (currentTime > block.timestamp) revert ERC4626SharePriceOracle__FuturePerformData(); // See if we are updating because of staleness. uint256 timeDelta = currentTime - currentObservation.timestamp; if (timeDelta >= heartbeat) upkeepConditionMet = true; // Use the old answer to calculate cumulative. uint256 currentCumulative = currentObservation.cumulative + (_answer * timeDelta); if (currentCumulative > type(uint192).max) revert ERC4626SharePriceOracle__CumulativeTooLarge(); currentObservation.cumulative = uint192(currentCumulative); currentObservation.timestamp = currentTime; uint256 timeDeltaSincePreviousObservation = currentTime - observations[_getPreviousIndex(_currentIndex, _observationsLength)].timestamp; // See if we need to advance to the next cumulative. if (timeDeltaSincePreviousObservation >= heartbeat) { uint16 nextIndex = _getNextIndex(_currentIndex, _observationsLength); currentIndex = nextIndex; // Update memory variable for event. _currentIndex = nextIndex; // Update newest cumulative. Observation storage newObservation = observations[nextIndex]; newObservation.cumulative = uint192(currentCumulative); newObservation.timestamp = currentTime; upkeepConditionMet = true; } if (!upkeepConditionMet) revert ERC4626SharePriceOracle__NoUpkeepConditionMet(); (uint256 timeWeightedAverageAnswer, bool isNotSafeToUse) = _getTimeWeightedAverageAnswer( sharePrice, _currentIndex, _observationsLength ); // See if kill switch should be activated based on change between proposed answer and time weighted average answer. if (!isNotSafeToUse && _checkIfKillSwitchShouldBeTriggered(sharePrice, timeWeightedAverageAnswer)) return; emit OracleUpdated(block.timestamp, currentTime, sharePrice, timeWeightedAverageAnswer, isNotSafeToUse); } //============================== ORACLE VIEW FUNCTIONS =============================== /** * @notice Get the latest answer, time weighted average answer, and bool indicating whether they can be safely used. */ function getLatest() external view returns (uint256 ans, uint256 timeWeightedAverageAnswer, bool notSafeToUse) { // Read state from one slot. ans = answer; uint16 _currentIndex = currentIndex; uint16 _observationsLength = observationsLength; bool _killSwitch = killSwitch; if (_killSwitch) return (0, 0, true); if (_checkSequencer()) return (0, 0, true); // Check if answer is stale, if so set notSafeToUse to true, and return. uint256 timeDeltaSinceLastUpdated = block.timestamp - observations[currentIndex].timestamp; // Note add in the grace period here, because it can take time for the upkeep TX to go through. if (timeDeltaSinceLastUpdated > (heartbeat + gracePeriod)) return (0, 0, true); (timeWeightedAverageAnswer, notSafeToUse) = _getTimeWeightedAverageAnswer( ans, _currentIndex, _observationsLength ); if (notSafeToUse) return (0, 0, true); } /** * @notice Get the latest answer, and bool indicating whether answer is safe to use or not. */ function getLatestAnswer() external view returns (uint256, bool) { uint256 _answer = answer; bool _killSwitch = killSwitch; if (_killSwitch) return (0, true); if (_checkSequencer()) return (0, true); // Check if answer is stale, if so set notSafeToUse to true, and return. uint256 timeDeltaSinceLastUpdated = block.timestamp - observations[currentIndex].timestamp; // Note add in the grace period here, because it can take time for the upkeep TX to go through. if (timeDeltaSinceLastUpdated > (heartbeat + gracePeriod)) return (0, true); return (_answer, false); } //============================== INTERNAL HELPER FUNCTIONS =============================== /** * @notice Get the next index of observations array. */ function _getNextIndex(uint16 _currentIndex, uint16 _length) internal pure returns (uint16 nextIndex) { nextIndex = (_currentIndex == _length - 1) ? 0 : _currentIndex + 1; } /** * @notice Get the previous index of observations array. */ function _getPreviousIndex(uint16 _currentIndex, uint16 _length) internal pure returns (uint16 previousIndex) { previousIndex = (_currentIndex == 0) ? _length - 1 : _currentIndex - 1; } /** * @notice Use observations to get the time weighted average answer. */ function _getTimeWeightedAverageAnswer( uint256 _answer, uint16 _currentIndex, uint16 _observationsLength ) internal view returns (uint256 timeWeightedAverageAnswer, bool notSafeToUse) { // Read observations from storage. Observation memory mostRecentlyCompletedObservation = observations[ _getPreviousIndex(_currentIndex, _observationsLength) ]; Observation memory oldestObservation = observations[_getNextIndex(_currentIndex, _observationsLength)]; // Data is not set. if (oldestObservation.timestamp == 1) return (0, true); // Make sure that the old observations we are using are not too stale. uint256 timeDelta = mostRecentlyCompletedObservation.timestamp - oldestObservation.timestamp; /// @dev use _length - 2 because /// remove 1 because observations array stores the current pending observation. /// remove 1 because we are really interested in the time between observations. uint256 minDuration = heartbeat * (_observationsLength - 2); uint256 maxDuration = minDuration + gracePeriod; // Data is too new if (timeDelta < minDuration) return (0, true); // Data is too old if (timeDelta > maxDuration) return (0, true); Observation memory latestObservation = observations[_currentIndex]; uint192 latestCumulative = latestObservation.cumulative + uint192((_answer * (block.timestamp - latestObservation.timestamp))); timeWeightedAverageAnswer = (latestCumulative - oldestObservation.cumulative) / (block.timestamp - oldestObservation.timestamp); } /** * @notice Get the target ERC4626's share price using totalAssets, and totalSupply. */ function _getTargetSharePrice() internal view returns (uint216 sharePrice) { uint256 totalShares = target.totalSupply(); // Get total Assets but scale it up to decimals decimals of precision. uint256 totalAssets = target.totalAssets().changeDecimals(targetDecimals, decimals); if (totalShares == 0) return 0; uint256 _sharePrice = ONE_SHARE.mulDivDown(totalAssets, totalShares); if (_sharePrice > type(uint216).max) revert ERC4626SharePriceOracle__SharePriceTooLarge(); sharePrice = uint216(_sharePrice); } /** * @notice Activate the kill switch if `proposedAnswer` is extreme when compared to `answerToCompareAgainst` * @return bool indicating whether calling function should immediately exit or not. */ function _checkIfKillSwitchShouldBeTriggered( uint256 proposedAnswer, uint256 answerToCompareAgainst ) internal returns (bool) { if ( proposedAnswer < answerToCompareAgainst.mulDivDown(allowedAnswerChangeLower, 1e4) || proposedAnswer > answerToCompareAgainst.mulDivDown(allowedAnswerChangeUpper, 1e4) ) { killSwitch = true; emit KillSwitchActivated( proposedAnswer, answerToCompareAgainst.mulDivDown(allowedAnswerChangeLower, 1e4), answerToCompareAgainst.mulDivDown(allowedAnswerChangeUpper, 1e4) ); return true; } return false; } /** * @notice Checks if the sequencer is down, or if the grace period is not met. * @return bool indicating if the sequencer has a problem */ function _checkSequencer() internal view returns (bool) { if (address(sequencerUptimeFeed) != address(0)) { (, int256 sequencerAnswer, uint256 startedAt, , ) = sequencerUptimeFeed.latestRoundData(); // This check should make TXs from L1 to L2 revert if someone tried interacting with the cellar while the sequencer is down. // Answer == 0: Sequencer is up // Answer == 1: Sequencer is down if (sequencerAnswer == 1) { return true; } // Make sure the grace period has passed after the // sequencer is back up. uint256 timeSinceUp = block.timestamp - startedAt; if (timeSinceUp <= sequencerGracePeriod) { return true; } } // If we made it this far, the sequencer is fine, and or it is not set. return false; } }
// 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 pragma solidity ^0.8.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // 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] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (0 - denominator) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } 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 // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use 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. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // 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 precoditions 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 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { error T(); error R(); /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { unchecked { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); if (absTick > uint256(int256(MAX_TICK))) revert T(); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { unchecked { // second inequality must be < because the price can never reach the price at the max tick if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R(); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol'; import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol'; import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol'; import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol'; import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol'; import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol'; import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolErrors, IUniswapV3PoolEvents { }
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount ) external returns (bool); /** * @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); }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Simple single owner authorization mixin. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol) abstract contract Owned { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event OwnershipTransferred(address indexed user, address indexed newOwner); /*////////////////////////////////////////////////////////////// OWNERSHIP STORAGE //////////////////////////////////////////////////////////////*/ address public owner; modifier onlyOwner() virtual { require(msg.sender == owner, "UNAUTHORIZED"); _; } /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(address _owner) { owner = _owner; emit OwnershipTransferred(address(0), _owner); } /*////////////////////////////////////////////////////////////// OWNERSHIP LOGIC //////////////////////////////////////////////////////////////*/ function transferOwnership(address newOwner) public virtual onlyOwner { owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AutomationCompatibleInterface { /** * @notice method that is simulated by the keepers to see if any work actually * needs to be performed. This method does does not actually need to be * executable, and since it is only ever simulated it can consume lots of gas. * @dev To ensure that it is never called, you may want to add the * cannotExecute modifier from KeeperBase to your implementation of this * method. * @param checkData specified in the upkeep registration so it is always the * same for a registered upkeep. This can easily be broken down into specific * arguments using `abi.decode`, so multiple upkeeps can be registered on the * same contract and easily differentiated by the contract. * @return upkeepNeeded boolean to indicate whether the keeper should call * performUpkeep or not. * @return performData bytes that the keeper should call performUpkeep with, if * upkeep is needed. If you would like to encode data to decode later, try * `abi.encode`. */ function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData); /** * @notice method that is actually executed by the keepers, via the registry. * The data returned by the checkUpkeep simulation will be passed into * this method to actually be executed. * @dev The input to this method should not be trusted, and the caller of the * method should not even be restricted to any single registry. Anyone should * be able call it, and the input should be validated, there is no guarantee * that the data passed in is the performData returned from checkUpkeep. This * could happen due to malicious keepers, racing keepers, or simply a state * change while the performUpkeep transaction is waiting for confirmation. * Always validate the data passed in. * @param performData is the data which was passed back from the checkData * simulation. If it is encoded, it can easily be decoded into other types by * calling `abi.decode`. This data should not be trusted, and should be * validated against the contract's current state. */ function performUpkeep(bytes calldata performData) external; }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; interface IRegistrar { struct RegistrationParams { string name; bytes encryptedEmail; address upkeepContract; uint32 gasLimit; address adminAddress; uint8 triggerType; bytes checkData; bytes triggerConfig; bytes offchainConfig; uint96 amount; } enum AutoApproveType { DISABLED, ENABLED_SENDER_ALLOWLIST, ENABLED_ALL } function registerUpkeep(RegistrationParams calldata requestParams) external returns (uint256 id); function setTriggerConfig( uint8 triggerType, AutoApproveType autoApproveType, uint32 autoApproveMaxAllowed ) external; function owner() external view returns (address); function approve( string memory name, address upkeepContract, uint32 gasLimit, address adminAddress, uint8 triggerType, bytes calldata checkData, bytes memory triggerConfig, bytes calldata offchainConfig, bytes32 hash ) external; }
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.21; interface IRegistry { struct UpkeepInfo { address target; uint32 executeGas; bytes checkData; uint96 balance; address admin; uint64 maxValidBlocknumber; uint32 lastPerformBlockNumber; uint96 amountSpent; bool paused; bytes offchainConfig; } function getForwarder(uint256 upkeepID) external view returns (address forwarder); function getUpkeep(uint256 id) external view returns (UpkeepInfo memory upkeepInfo); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// @return tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// @return observationIndex The index of the last oracle observation that was written, /// @return observationCardinality The current maximum number of observations stored in the pool, /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// @return feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks /// @return The liquidity at the current price of the pool function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper /// @return liquidityNet how much liquidity changes when the pool price crosses the tick, /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// @return secondsOutside the seconds spent on the other side of the tick from the current tick, /// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return liquidity The amount of liquidity in the position, /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// @return initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Errors emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolErrors { error LOK(); error TLU(); error TLM(); error TUM(); error AI(); error M0(); error M1(); error AS(); error IIA(); error L(); error F0(); error F1(); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
{ "remappings": [ "@solmate/=lib/solmate/src/", "@forge-std/=lib/forge-std/src/", "@ds-test/=lib/forge-std/lib/ds-test/src/", "ds-test/=lib/forge-std/lib/ds-test/src/", "@openzeppelin/=lib/openzeppelin-contracts/", "@uniswap/v3-periphery/=lib/v3-periphery/", "@uniswap/v3-core/=lib/v3-core/", "@chainlink/=lib/chainlink/", "@uniswapV3P/=lib/v3-periphery/contracts/", "@uniswapV3C/=lib/v3-core/contracts/", "@balancer/=lib/balancer-v2-monorepo/pkg/", "@ccip/=lib/ccip/", "@balancer-labs/=lib/balancer-v2-monorepo/../../node_modules/@balancer-labs/", "axelar-gmp-sdk-solidity/=lib/axelar-gmp-sdk-solidity/contracts/", "balancer-v2-monorepo/=lib/balancer-v2-monorepo/", "ccip/=lib/ccip/contracts/", "chainlink/=lib/chainlink/integration-tests/contracts/ethereum/src/", "forge-std/=lib/forge-std/src/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/", "solmate/=lib/solmate/src/", "v3-core/=lib/v3-core/contracts/", "v3-periphery/=lib/v3-periphery/contracts/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "shanghai", "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"contract Registry","name":"_registry","type":"address"},{"internalType":"contract ERC20","name":"_asset","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint32","name":"_holdingPosition","type":"uint32"},{"internalType":"bytes","name":"_holdingPositionConfig","type":"bytes"},{"internalType":"uint256","name":"_initialDeposit","type":"uint256"},{"internalType":"uint64","name":"_strategistPlatformCut","type":"uint64"},{"internalType":"uint192","name":"_shareSupplyCap","type":"uint192"},{"internalType":"address","name":"_balancerVault","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CellarWithMultiAssetDeposit__AlternativeAssetFeeTooLarge","type":"error"},{"inputs":[],"name":"CellarWithMultiAssetDeposit__AlternativeAssetNotSupported","type":"error"},{"inputs":[],"name":"CellarWithMultiAssetDeposit__CallDataLengthNotSupported","type":"error"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"address","name":"expectedAsset","type":"address"}],"name":"Cellar__AssetMismatch","type":"error"},{"inputs":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"Cellar__CallToAdaptorNotAllowed","type":"error"},{"inputs":[],"name":"Cellar__CallerNotBalancerVault","type":"error"},{"inputs":[],"name":"Cellar__ContractNotShutdown","type":"error"},{"inputs":[],"name":"Cellar__ContractShutdown","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Cellar__DebtMismatch","type":"error"},{"inputs":[],"name":"Cellar__ExpectedAddressDoesNotMatchActual","type":"error"},{"inputs":[],"name":"Cellar__ExternalInitiator","type":"error"},{"inputs":[],"name":"Cellar__FailedToForceOutPosition","type":"error"},{"inputs":[{"internalType":"address","name":"illiquidPosition","type":"address"}],"name":"Cellar__IlliquidWithdraw","type":"error"},{"inputs":[{"internalType":"uint256","name":"assetsOwed","type":"uint256"}],"name":"Cellar__IncompleteWithdraw","type":"error"},{"inputs":[],"name":"Cellar__InvalidFee","type":"error"},{"inputs":[],"name":"Cellar__InvalidFeeCut","type":"error"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"Cellar__InvalidHoldingPosition","type":"error"},{"inputs":[{"internalType":"uint256","name":"requested","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"Cellar__InvalidRebalanceDeviation","type":"error"},{"inputs":[],"name":"Cellar__InvalidShareSupplyCap","type":"error"},{"inputs":[],"name":"Cellar__MinimumConstructorMintNotMet","type":"error"},{"inputs":[],"name":"Cellar__OracleFailure","type":"error"},{"inputs":[],"name":"Cellar__Paused","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Cellar__PositionAlreadyUsed","type":"error"},{"inputs":[{"internalType":"uint256","name":"maxPositions","type":"uint256"}],"name":"Cellar__PositionArrayFull","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"},{"internalType":"uint256","name":"sharesRemaining","type":"uint256"}],"name":"Cellar__PositionNotEmpty","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Cellar__PositionNotInCatalogue","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Cellar__PositionNotUsed","type":"error"},{"inputs":[],"name":"Cellar__RemovingHoldingPosition","type":"error"},{"inputs":[],"name":"Cellar__SettingValueToRegistryIdZeroIsProhibited","type":"error"},{"inputs":[],"name":"Cellar__ShareSupplyCapExceeded","type":"error"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"min","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"Cellar__TotalAssetDeviatedOutsideRange","type":"error"},{"inputs":[{"internalType":"uint256","name":"current","type":"uint256"},{"internalType":"uint256","name":"expected","type":"uint256"}],"name":"Cellar__TotalSharesMustRemainConstant","type":"error"},{"inputs":[],"name":"Cellar__ZeroAssets","type":"error"},{"inputs":[],"name":"Cellar__ZeroShares","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"adaptor","type":"address"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"AdaptorCalled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"adaptor","type":"address"},{"indexed":false,"internalType":"bool","name":"inCatalogue","type":"bool"}],"name":"AdaptorCatalogueAltered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"asset","type":"address"}],"name":"AlternativeAssetDropped","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"uint32","name":"holdingPosition","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"depositFee","type":"uint32"}],"name":"AlternativeAssetUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"contract Authority","name":"newAuthority","type":"address"}],"name":"AuthorityUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","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":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"depositAsset","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"MultiAssetDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"position","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"}],"name":"PositionAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"positionId","type":"uint32"},{"indexed":false,"internalType":"bool","name":"inCatalogue","type":"bool"}],"name":"PositionCatalogueAltered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"position","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"}],"name":"PositionRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"newPosition1","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"newPosition2","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"index2","type":"uint256"}],"name":"PositionSwapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldDeviation","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newDeviation","type":"uint256"}],"name":"RebalanceDeviationChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newOracle","type":"address"}],"name":"SharePriceOracleUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isShutdown","type":"bool"}],"name":"ShutdownChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldPayoutAddress","type":"address"},{"indexed":false,"internalType":"address","name":"newPayoutAddress","type":"address"}],"name":"StrategistPayoutAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"oldPlatformCut","type":"uint64"},{"indexed":false,"internalType":"uint64","name":"newPlatformCut","type":"uint64"}],"name":"StrategistPlatformCutChanged","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":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","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":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"addAdaptorToCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"uint32","name":"positionId","type":"uint32"},{"internalType":"bytes","name":"configurationData","type":"bytes"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"addPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"addPositionToCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"","type":"address"}],"name":"alternativeAssetData","outputs":[{"internalType":"bool","name":"isSupported","type":"bool"},{"internalType":"uint32","name":"holdingPosition","type":"uint32"},{"internalType":"uint32","name":"depositFee","type":"uint32"}],"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":"contract ERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"authority","outputs":[{"internalType":"contract Authority","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"blockExternalReceiver","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"checkTotalAssets","type":"bool"},{"internalType":"uint16","name":"allowableRange","type":"uint16"},{"internalType":"address","name":"expectedPriceRouter","type":"address"}],"name":"cachePriceRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"adaptor","type":"address"},{"internalType":"bytes[]","name":"callData","type":"bytes[]"}],"internalType":"struct Cellar.AdaptorCall[]","name":"data","type":"tuple[]"}],"name":"callOnAdaptor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint192","name":"_newShareSupplyCap","type":"uint192"}],"name":"decreaseShareSupplyCap","outputs":[],"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":"contract ERC20","name":"_alternativeAsset","type":"address"}],"name":"dropAlternativeAssetData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeData","outputs":[{"internalType":"uint64","name":"strategistPlatformCut","type":"uint64"},{"internalType":"uint64","name":"platformFee","type":"uint64"},{"internalType":"uint64","name":"lastAccrual","type":"uint64"},{"internalType":"address","name":"strategistPayoutAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"uint32","name":"positionId","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"forcePositionOut","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getCreditPositions","outputs":[{"internalType":"uint32[]","name":"","type":"uint32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDebtPositions","outputs":[{"internalType":"uint32[]","name":"","type":"uint32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"holdingPosition","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ignorePause","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint192","name":"_newShareSupplyCap","type":"uint192"}],"name":"increaseShareSupplyCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"initiateShutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"isPositionUsed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isShutdown","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liftShutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"locked","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"depositAsset","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"multiAssetDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"depositAsset","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewMultiAssetDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"priceRouter","outputs":[{"internalType":"contract PriceRouter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"uint256[]","name":"feeAmounts","type":"uint256[]"},{"internalType":"bytes","name":"userData","type":"bytes"}],"name":"receiveFlashLoan","outputs":[],"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":[],"name":"registry","outputs":[{"internalType":"contract Registry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"removeAdaptorFromCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"removePosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"removePositionFromCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"_alternativeAsset","type":"address"},{"internalType":"uint32","name":"_alternativeHoldingPosition","type":"uint32"},{"internalType":"uint32","name":"_alternativeAssetFee","type":"uint32"}],"name":"setAlternativeAssetData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract Authority","name":"newAuthority","type":"address"}],"name":"setAuthority","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"setHoldingPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newDeviation","type":"uint256"}],"name":"setRebalanceDeviation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_registryId","type":"uint256"},{"internalType":"contract ERC4626SharePriceOracle","name":"_sharePriceOracle","type":"address"}],"name":"setSharePriceOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"payout","type":"address"}],"name":"setStrategistPayoutAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"cut","type":"uint64"}],"name":"setStrategistPlatformCut","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sharePriceOracle","outputs":[{"internalType":"contract ERC4626SharePriceOracle","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"shareSupplyCap","outputs":[{"internalType":"uint192","name":"","type":"uint192"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"index1","type":"uint32"},{"internalType":"uint32","name":"index2","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"swapPositions","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"toggleIgnorePause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssetsWithdrawable","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"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"},{"stateMutability":"payable","type":"receive"}]
Contract Creation Code
6101c0604052670a688906bd8b000061014052662386f26fc10000610160525f6101808190526101a052601080546001600160c01b0319166e2386f26fc100000a688906bd8b0000179055601180546001600160a01b0319169055660110d9316ec00060125534801562000071575f80fd5b50604051620076dd380380620076dd833981016040819052620000949162001103565b8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a89898989898989898989335f8989898181846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000102573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000128919062001228565b5f620001358482620012d6565b506001620001448382620012d6565b5060ff81166080524660a0526200015a62000386565b60c0525050506001600160a01b0392831660e0525050600680548483166001600160a01b0319918216811790925560078054938516939091169290921790915560405133905f8051602062007696833981519152905f90a36040516001600160a01b0382169033907fa3396fd7f6e0a21b50e5089d2da70d5ac0a3bbbd1f617a93f134b76389980198905f90a350506001600160a01b038916610100819052604051635c9fcd8560e11b81526002600482015263b93f9b0a90602401602060405180830381865afa15801562000232573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200025891906200139e565b600980546001600160a01b0319166001600160a01b0392909216919091179055620002838562000420565b620002915f868682620004e7565b6200029c85620007b0565b600880546001600160c01b0319166001600160c01b038316179055612710831015620002db57604051632d0d251960e11b815260040160405180910390fd5b620002f26001600160a01b0389168b3086620008c6565b620002fe338462000957565b6200030a8584620009c2565b601080546001600160401b0319166001600160401b038416179055620003308a62000a58565b5050505050505050505050505050505050505050806001600160a01b0316610120816001600160a01b03168152505050505050505050505050505050505050505050505050505050505050505050505062001646565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f604051620003b89190620013bc565b6040805191829003822060208301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b6200042a62000ae5565b61010051604051635159d87f60e11b815263ffffffff831660048201526001600160a01b039091169063a2b3b0fe906024015f6040518083038186803b15801562000473575f80fd5b505afa15801562000486573d5f803e3d5ffd5b5050505063ffffffff81165f818152600e6020908152604091829020805460ff191660019081179091558251938452908301527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f910160405180910390a150565b620004f162000ae5565b620004fb62000b3b565b63ffffffff83165f908152600c602052604090205460ff16156200053f5760405163335894fb60e11b815263ffffffff841660048201526024015b60405180910390fd5b63ffffffff83165f908152600e602052604090205460ff166200057e57604051631f9db01d60e31b815263ffffffff8416600482015260240162000536565b610100516040516385ae5d5760e01b815263ffffffff851660048201525f91829182916001600160a01b0316906385ae5d57906024015f60405180830381865afa158015620005cf573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052620005f8919081019062001446565b925092509250831515821515146200062c57604051632b1d0bd360e11b815263ffffffff8716600482015260240162000536565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600d9092529490208351815492511515600160a01b026001600160a81b031990931693169290921717815591519091906001820190620006a79082620012d6565b5060608201516002820190620006be9082620012d6565b5090505081156200070557600b54602011620006f15760405163f025236d60e01b81526020600482015260240162000536565b620006ff600b888862000b67565b6200073b565b600a546020116200072d5760405163f025236d60e01b81526020600482015260240162000536565b6200073b600a888862000b67565b63ffffffff86165f908152600c602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb906200079f9088908a9063ffffffff92831681529116602082015260400190565b60405180910390a150505050505050565b620007ba62000ae5565b63ffffffff81165f908152600c602052604090205460ff16620007f9576040516370abe85960e01b815263ffffffff8216600482015260240162000536565b60e0516001600160a01b0316620008108262000d3c565b6001600160a01b0316146200085a5760e0516200082d8262000d3c565b60405163298473c760e11b81526001600160a01b0392831660048201529116602482015260440162000536565b63ffffffff81165f908152600d6020526040902054600160a01b900460ff1615620008a157604051630a42c0f960e41b815263ffffffff8216600482015260240162000536565b6008805463ffffffff909216600160e01b026001600160e01b03909216919091179055565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f511416171691505080620009505760405162461bcd60e51b815260206004820152601460248201527f5452414e534645525f46524f4d5f4641494c4544000000000000000000000000604482015260640162000536565b5050505050565b8060025f8282546200096a9190620014be565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b63ffffffff82165f908152600d602052604090819020805491516001600160a01b039092169162000a52916369445c3160e01b9162000a0f91869160018201916002019060240162001555565b60408051808303601f190181529190526020810180516001600160e01b0319939093166001600160e01b039384161790526001600160a01b0384169162000dce16565b50505050565b62000a6f336001600160e01b03195f351662000dff565b62000aac5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640162000536565b600680546001600160a01b0319166001600160a01b03831690811790915560405133905f8051602062007696833981519152905f90a350565b62000afc336001600160e01b03195f351662000dff565b62000b395760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640162000536565b565b600854600160c81b900460ff161562000b39576040516337a5332d60e11b815260040160405180910390fd5b8254801562000cfc57838062000b7f60018462001583565b8154811062000b925762000b9262001599565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a909204909316021790559062000bf5908362001583565b90505b8363ffffffff1681111562000ca8578462000c1560018362001583565b8154811062000c285762000c2862001599565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1685828154811062000c615762000c6162001599565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808062000c9f90620015ad565b91505062000bf8565b5081848463ffffffff168154811062000cc55762000cc562001599565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff16021790555062000a52565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b63ffffffff81165f908152600d60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf9162000d859160010190600401620015c5565b602060405180830381865afa15801562000da1573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000dc791906200139e565b9392505050565b606062000df68383604051806060016040528060278152602001620076b66027913962000eba565b90505b92915050565b6007545f906001600160a01b0316801580159062000e99575060405163b700961360e01b81526001600160a01b0385811660048301523060248301526001600160e01b03198516604483015282169063b700961390606401602060405180830381865afa15801562000e73573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000e999190620015d9565b8062000eb257506006546001600160a01b038581169116145b949350505050565b60605f80856001600160a01b03168560405162000ed89190620015f5565b5f60405180830381855af49150503d805f811462000f12576040519150601f19603f3d011682016040523d82523d5f602084013e62000f17565b606091505b50909250905062000f2b8683838762000f35565b9695505050505050565b6060831562000fa85782515f0362000fa0576001600160a01b0385163b62000fa05760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640162000536565b508162000eb2565b62000eb2838381511562000fbf5781518083602001fd5b8060405162461bcd60e51b815260040162000536919062001612565b6001600160a01b038116811462000ff0575f80fd5b50565b8051620010008162000fdb565b919050565b634e487b7160e01b5f52604160045260245ffd5b5f5b83811015620010355781810151838201526020016200101b565b50505f910152565b5f82601f8301126200104d575f80fd5b81516001600160401b03808211156200106a576200106a62001005565b604051601f8301601f19908116603f0116810190828211818310171562001095576200109562001005565b81604052838152866020858801011115620010ae575f80fd5b62000f2b84602083016020890162001019565b805163ffffffff8116811462001000575f80fd5b80516001600160401b038116811462001000575f80fd5b80516001600160c01b038116811462001000575f80fd5b5f805f805f805f805f805f6101608c8e0312156200111f575f80fd5b6200112a8c62000ff3565b9a506200113a60208d0162000ff3565b99506200114a60408d0162000ff3565b60608d01519099506001600160401b0381111562001166575f80fd5b620011748e828f016200103d565b60808e015190995090506001600160401b0381111562001192575f80fd5b620011a08e828f016200103d565b975050620011b160a08d01620010c1565b60c08d01519096506001600160401b03811115620011cd575f80fd5b620011db8e828f016200103d565b95505060e08c01519350620011f46101008d01620010d5565b9250620012056101208d01620010ec565b9150620012166101408d0162000ff3565b90509295989b509295989b9093969950565b5f6020828403121562001239575f80fd5b815160ff8116811462000dc7575f80fd5b600181811c908216806200125f57607f821691505b6020821081036200127e57634e487b7160e01b5f52602260045260245ffd5b50919050565b601f821115620012d1575f81815260208120601f850160051c81016020861015620012ac5750805b601f850160051c820191505b81811015620012cd57828155600101620012b8565b5050505b505050565b81516001600160401b03811115620012f257620012f262001005565b6200130a816200130384546200124a565b8462001284565b602080601f83116001811462001340575f8415620013285750858301515b5f19600386901b1c1916600185901b178555620012cd565b5f85815260208120601f198616915b8281101562001370578886015182559484019460019091019084016200134f565b50858210156200138e57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f60208284031215620013af575f80fd5b815162000dc78162000fdb565b5f808354620013cb816200124a565b60018281168015620013e65760018114620013fc576200142a565b60ff19841687528215158302870194506200142a565b875f526020805f205f5b85811015620014215781548a82015290840190820162001406565b50505082870194505b50929695505050505050565b8051801515811462001000575f80fd5b5f805f6060848603121562001459575f80fd5b8351620014668162000fdb565b9250620014766020850162001436565b60408501519092506001600160401b0381111562001492575f80fd5b620014a0868287016200103d565b9150509250925092565b634e487b7160e01b5f52601160045260245ffd5b8082018082111562000df95762000df9620014aa565b5f8154620014e2816200124a565b8085526020600183811680156200150257600181146200151d576200154a565b60ff1985168884015283151560051b8801830195506200154a565b865f52825f205f5b85811015620015425781548a820186015290830190840162001525565b890184019650505b505050505092915050565b838152606060208201525f6200156f6060830185620014d4565b828103604084015262000f2b8185620014d4565b8181038181111562000df95762000df9620014aa565b634e487b7160e01b5f52603260045260245ffd5b5f81620015be57620015be620014aa565b505f190190565b602081525f62000df66020830184620014d4565b5f60208284031215620015ea575f80fd5b62000df68262001436565b5f82516200160881846020870162001019565b9190910192915050565b602081525f82518060208401526200163281604085016020870162001019565b601f01601f19169190910160400192915050565b60805160a05160c05160e0516101005161012051615f8a6200170c5f395f8181612f2f0152612fbe01525f81816109200152818161179e01528181611af5015281816122e9015281816125bc0152818161288c0152818161329b015261434201525f81816106b801528181610f9401528181610fd501528181611da0015281816121de015281816134b10152818161376401528181613a8b01528181613fa1015261497601525f6114b001525f61148001525f818161062101526149f20152615f8a5ff3fe60806040526004361061042f575f3560e01c8063855bccb31161022b578063ba08765211610129578063d446bbcc116100b3578063e753e60011610078578063e753e60014610d9a578063ef8b30f714610c53578063f04f270714610e1b578063f2fde38b14610e3a578063f5743bc914610e59575f80fd5b8063d446bbcc14610cd0578063d505accf14610d07578063d7d4bf4514610d26578063d905777e14610d45578063dd62ed3e14610d64575f80fd5b8063c63d75b6116100f9578063c63d75b614610c34578063c6e6f59214610c53578063ce96cb7714610c72578063cf30901214610c91578063d1e8840414610cb1575f80fd5b8063ba08765214610bb7578063bf7e214f14610bd6578063bf86d69014610bf5578063c588d8d614610c15575f80fd5b8063a373e3ff116101b5578063b0a75d361161017a578063b0a75d3614610b27578063b187bd2614610b46578063b3d7f6b914610b5a578063b460af9414610b79578063b5292a9914610b98575f80fd5b8063a373e3ff14610aa2578063a8144e4814610ab6578063a9059cbb14610aca578063ac9650d814610ae9578063b0646e2714610b08575f80fd5b806395d89b41116101fb57806395d89b41146109f85780639955a9d414610a0c5780639959af9414610a2b5780639c5f00c214610a4b578063a07bee0b14610a83575f80fd5b8063855bccb31461096d5780638da5cb5b1461098c57806393bbeac0146109ab57806394bf804d146109d9575f80fd5b80633d8ab1e5116103385780635e2c576e116102c257806371e99dc21161028757806371e99dc2146108bd5780637a9e5e4b146108d15780637ab92915146108f05780637b1039991461090f5780637ecebe0014610942575f80fd5b80635e2c576e146107d55780635f6b88a0146107e95780636419111e146108085780636e553f651461087357806370a0823114610892575f80fd5b80634cdad506116103085780634cdad506146104a35780634e84befe14610759578063501eb4fe14610778578063530a371414610797578063575bbce6146107b6575f80fd5b80633d8ab1e5146106da5780633e3382ba146106f9578063402d267d1461071a5780634c4602da14610739575f80fd5b8063196e8285116103b9578063313ce56711610389578063313ce5671461061057806333e15be2146106555780633644e51514610674578063379e0b131461068857806338d52e0f146106a7575f80fd5b8063196e82851461057c578063217bb34d146105b357806323b872dd146105d25780632b91c5de146105f1575f80fd5b8063095ea7b3116103ff578063095ea7b3146104c25780630a28a477146104f15780630a680e1814610510578063150b7a021461052457806318160ddd14610567575f80fd5b806301e1d1141461043a57806306fdde03146104615780630780fd3a1461048257806307a2d13a146104a3575f80fd5b3661043657005b5f80fd5b348015610445575f80fd5b5061044e610e78565b6040519081526020015b60405180910390f35b34801561046c575f80fd5b50610475610ec2565b6040516104589190614ea5565b34801561048d575f80fd5b506104a161049c366004614ecf565b610f4d565b005b3480156104ae575f80fd5b5061044e6104bd366004614ee8565b611093565b3480156104cd575f80fd5b506104e16104dc366004614f13565b6110b6565b6040519015158152602001610458565b3480156104fc575f80fd5b5061044e61050b366004614ee8565b611122565b34801561051b575f80fd5b506104a161113d565b34801561052f575f80fd5b5061054e61053e366004615021565b630a85bd0160e11b949350505050565b6040516001600160e01b03199091168152602001610458565b348015610572575f80fd5b5061044e60025481565b348015610587575f80fd5b5060135461059b906001600160a01b031681565b6040516001600160a01b039091168152602001610458565b3480156105be575f80fd5b506104a16105cd366004615088565b611197565b3480156105dd575f80fd5b506104e16105ec3660046150a3565b6111fe565b3480156105fc575f80fd5b5061044e61060b3660046150e1565b6112d8565b34801561061b575f80fd5b506106437f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff9091168152602001610458565b348015610660575f80fd5b506104a161066f36600461512d565b6113a2565b34801561067f575f80fd5b5061044e61147d565b348015610693575f80fd5b506104a16106a2366004615162565b6114d2565b3480156106b2575f80fd5b5061059b7f000000000000000000000000000000000000000000000000000000000000000081565b3480156106e5575f80fd5b506104a16106f4366004615088565b611777565b348015610704575f80fd5b5061070d61184e565b604051610458919061519b565b348015610725575f80fd5b5061044e610734366004615088565b6118cf565b348015610744575f80fd5b506008546104e190600160d81b900460ff1681565b348015610764575f80fd5b506104a161077336600461522b565b61196b565b348015610783575f80fd5b506104a1610792366004614ecf565b611ad2565b3480156107a2575f80fd5b506104a16107b1366004614ee8565b611baa565b3480156107c1575f80fd5b506104a16107d0366004615269565b611c32565b3480156107e0575f80fd5b506104a1611c8c565b3480156107f4575f80fd5b506104a1610803366004615088565b611cfb565b348015610813575f80fd5b5061084f610822366004615088565b60146020525f908152604090205460ff81169063ffffffff61010082048116916501000000000090041683565b60408051931515845263ffffffff9283166020850152911690820152606001610458565b34801561087e575f80fd5b5061044e61088d36600461528f565b611d59565b34801561089d575f80fd5b5061044e6108ac366004615088565b60036020525f908152604090205481565b3480156108c8575f80fd5b5061070d611dee565b3480156108dc575f80fd5b506104a16108eb366004615088565b611e4a565b3480156108fb575f80fd5b5061044e61090a366004614f13565b611f2f565b34801561091a575f80fd5b5061059b7f000000000000000000000000000000000000000000000000000000000000000081565b34801561094d575f80fd5b5061044e61095c366004615088565b60056020525f908152604090205481565b348015610978575f80fd5b506104a16109873660046152b2565b611f7b565b348015610997575f80fd5b5060065461059b906001600160a01b031681565b3480156109b6575f80fd5b506104e16109c5366004614ee8565b600c6020525f908152604090205460ff1681565b3480156109e4575f80fd5b5061044e6109f336600461528f565b612124565b348015610a03575f80fd5b50610475612228565b348015610a17575f80fd5b506104a1610a263660046152f4565b612235565b348015610a36575f80fd5b506008546104e190600160d01b900460ff1681565b348015610a56575f80fd5b50600854610a6e90600160e01b900463ffffffff1681565b60405163ffffffff9091168152602001610458565b348015610a8e575f80fd5b506104a1610a9d366004615162565b6124fb565b348015610aad575f80fd5b506104a1612656565b348015610ac1575f80fd5b5061044e612696565b348015610ad5575f80fd5b506104e1610ae4366004614f13565b6126d3565b348015610af4575f80fd5b506104a1610b0336600461522b565b612736565b348015610b13575f80fd5b506104a1610b22366004615269565b6127bb565b348015610b32575f80fd5b506104a1610b41366004615088565b6127f3565b348015610b51575f80fd5b506104e1612864565b348015610b65575f80fd5b5061044e610b74366004614ee8565b612902565b348015610b84575f80fd5b5061044e610b93366004615360565b61291e565b348015610ba3575f80fd5b506104a1610bb2366004615394565b61299b565b348015610bc2575f80fd5b5061044e610bd1366004615360565b612a3f565b348015610be1575f80fd5b5060075461059b906001600160a01b031681565b348015610c00575f80fd5b506008546104e190600160c81b900460ff1681565b348015610c20575f80fd5b506104a1610c2f3660046153ba565b612ac6565b348015610c3f575f80fd5b5061044e610c4e366004615088565b612b8e565b348015610c5e575f80fd5b5061044e610c6d366004614ee8565b612c02565b348015610c7d575f80fd5b5061044e610c8c366004615088565b612c1e565b348015610c9c575f80fd5b506008546104e190600160c01b900460ff1681565b348015610cbc575f80fd5b506104a1610ccb366004614ecf565b612c54565b348015610cdb575f80fd5b50600854610cef906001600160c01b031681565b6040516001600160c01b039091168152602001610458565b348015610d12575f80fd5b506104a1610d213660046153fb565b612caf565b348015610d31575f80fd5b5060095461059b906001600160a01b031681565b348015610d50575f80fd5b5061044e610d5f366004615088565b612eed565b348015610d6f575f80fd5b5061044e610d7e366004615467565b600460209081525f928352604080842090915290825290205481565b348015610da5575f80fd5b50601054601154610de2916001600160401b0380821692680100000000000000008304821692600160801b9004909116906001600160a01b031684565b604080516001600160401b039586168152938516602085015291909316908201526001600160a01b039091166060820152608001610458565b348015610e26575f80fd5b506104a1610e35366004615493565b612f24565b348015610e45575f80fd5b506104a1610e54366004615088565b61306c565b348015610e64575f80fd5b506104a1610e7336600461528f565b6130e8565b5f610e81613275565b600854600160c01b900460ff1615610eb45760405162461bcd60e51b8152600401610eab90615577565b60405180910390fd5b610ebd5f61332c565b905090565b5f8054610ece9061559b565b80601f0160208091040260200160405190810160405280929190818152602001828054610efa9061559b565b8015610f455780601f10610f1c57610100808354040283529160200191610f45565b820191905f5260205f20905b815481529060010190602001808311610f2857829003601f168201915b505050505081565b610f556137d7565b63ffffffff81165f908152600c602052604090205460ff16610f92576040516370abe85960e01b815263ffffffff82166004820152602401610eab565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610fc582613808565b6001600160a01b031614611029577f0000000000000000000000000000000000000000000000000000000000000000610ffd82613808565b60405163298473c760e11b81526001600160a01b03928316600482015291166024820152604401610eab565b63ffffffff81165f908152600d6020526040902054600160a01b900460ff161561106e57604051630a42c0f960e41b815263ffffffff82166004820152602401610eab565b6008805463ffffffff909216600160e01b026001600160e01b03909216919091179055565b5f805f61109f5f613895565b915091506110ae8483836139a9565b949350505050565b335f8181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906111109086815260200190565b60405180910390a35060015b92915050565b5f805f61112e5f613895565b915091506110ae8483836139b5565b6111456137d7565b61114d6139c1565b6008805460ff60c81b1916600160c81b179055604051600181527fb8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3c906020015b60405180910390a1565b61119f6137d7565b6001600160a01b0381165f81815260146020908152604091829020805468ffffffffffffffffff1916905590519182527f741bf5c2d606526029e0f199a3ddf6c7ebafa7edb2e1405174105f458195e67991015b60405180910390a150565b6001600160a01b0383165f9081526004602090815260408083203384529091528120545f1981146112575761123383826155e7565b6001600160a01b0386165f9081526004602090815260408083203384529091529020555b6001600160a01b0385165f908152600360205260408120805485929061127e9084906155e7565b90915550506001600160a01b038085165f81815260036020526040908190208054870190555190918716905f80516020615f35833981519152906112c59087815260200190565b60405180910390a3506001949350505050565b6008545f90600160c01b900460ff16156113045760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790555f808061132487876139ec565b92509250925061133887878585858a613b42565b604080516001600160a01b038a81168252602082018a905291810183905291955086169033907f385ba312edecbeeae57aca70f4fde3d83578697795291e74b1b4edb37d7291bf9060600160405180910390a350506008805460ff60c01b19169055509392505050565b6113aa6137d7565b5f816113f257600a8363ffffffff16815481106113c9576113c96155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16611430565b600b8363ffffffff168154811061140b5761140b6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90505f61143c82613bd2565b9050801561146c57604051631c7b946d60e31b815263ffffffff8316600482015260248101829052604401610eab565b611477848385613c58565b50505050565b5f7f000000000000000000000000000000000000000000000000000000000000000046146114ad57610ebd613d3a565b507f000000000000000000000000000000000000000000000000000000000000000090565b6114da6137d7565b5f80821561160357600b8463ffffffff16815481106114fb576114fb6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169150600b8563ffffffff168154811061153a5761153a6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690508181600b8763ffffffff168154811061157b5761157b6155fa565b905f5260205f209060089182820401919006600402600b8863ffffffff16815481106115a9576115a96155fa565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff1602179055505050611720565b600a8463ffffffff168154811061161c5761161c6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169150600a8563ffffffff168154811061165b5761165b6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690508181600a8763ffffffff168154811061169c5761169c6155fa565b905f5260205f209060089182820401919006600402600a8863ffffffff16815481106116ca576116ca6155fa565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff16021790555050505b6040805163ffffffff84811682528381166020830152878116828401528616606082015290517fb7c5df04749a3a06a9a7bf1a8142ccf2a4ee6cbf4709489e876a6e4eb3301e8a9181900360800190a15050505050565b61177f6137d7565b604051636777140560e11b81526001600160a01b0382811660048301527f0000000000000000000000000000000000000000000000000000000000000000169063ceee280a906024015f6040518083038186803b1580156117de575f80fd5b505afa1580156117f0573d5f803e3d5ffd5b505050506001600160a01b0381165f818152600f6020908152604091829020805460ff191660019081179091558251938452908301527f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7a91016111f3565b6060600b8054806020026020016040519081016040528092919081815260200182805480156118c557602002820191905f5260205f20905f905b82829054906101000a900463ffffffff1663ffffffff16815260200190600401906020826003010492830192600103820291508084116118885790505b5050505050905090565b6008545f90600160c81b900460ff16156118ea57505f919050565b6008546001600160c01b03166002600160c01b0319810161190e57505f1992915050565b5f8061191a6001613895565b91509150826001600160c01b0316811061193857505f949350505050565b5f61194c826001600160c01b0386166155e7565b90506119598184846139a9565b9695505050505050565b505050919050565b600854600160c01b900460ff16156119955760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790556119b06137d7565b6119b86139c1565b6119c0613275565b6008805460ff60d81b1916600160d81b1790555f8080806119e08161332c565b9050611a0b601254670de0b6b3a76400006119fb91906155e7565b8290670de0b6b3a7640000613dd2565b9350611a26601254670de0b6b3a76400006119fb919061560e565b6002549093509150611a429050611a3d858761575c565b613dff565b5f611a4c5f61332c565b905083811080611a5b57508281115b15611a8a5760405163628cc47560e11b8152600481018290526024810185905260448101849052606401610eab565b6002548214611aba57600254604051632b40145960e21b8152600481019190915260248101839052604401610eab565b50506008805463ff0000ff60c01b1916905550505050565b611ada6137d7565b604051635159d87f60e11b815263ffffffff821660048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a2b3b0fe906024015f6040518083038186803b158015611b3d575f80fd5b505afa158015611b4f573d5f803e3d5ffd5b5050505063ffffffff81165f818152600e6020908152604091829020805460ff191660019081179091558251938452908301527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f91016111f3565b611bb26137d7565b67016345785d8a0000811115611bec576040516302d2a90f60e51b81526004810182905267016345785d8a00006024820152604401610eab565b601280549082905560408051828152602081018490527fdf4be33b2e9e3dd4d9e0e85645aea428494a0644a72c51d6a15aedae6b66a3ff91015b60405180910390a15050565b611c3a6137d7565b6008546001600160c01b039081169082161115611c6a576040516334f1ec1b60e01b815260040160405180910390fd5b600880546001600160c01b0319166001600160c01b0392909216919091179055565b611c946137d7565b600854600160c81b900460ff16611cbe5760405163ec7165bf60e01b815260040160405180910390fd5b6008805460ff60c81b191690556040515f81527fb8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3c9060200161118d565b611d036137d7565b6001600160a01b0381165f818152600f60209081526040808320805460ff191690558051938452908301919091527f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7a91016111f3565b6008545f90600160c01b900460ff1615611d855760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790819055611dda907f00000000000000000000000000000000000000000000000000000000000000009085908190819063ffffffff600160e01b9091041687613b42565b6008805460ff60c01b191690559392505050565b6060600a8054806020026020016040519081016040528092919081815260200182805480156118c5575f918252602091829020805463ffffffff1684529082028301929091600491018084116118885790505050505050905090565b6006546001600160a01b0316331480611edc575060075460405163b700961360e01b81526001600160a01b039091169063b700961390611e9d90339030906001600160e01b03195f351690600401615768565b602060405180830381865afa158015611eb8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611edc9190615795565b611ee4575f80fd5b600780546001600160a01b0319166001600160a01b03831690811790915560405133907fa3396fd7f6e0a21b50e5089d2da70d5ac0a3bbbd1f617a93f134b76389980198905f90a350565b5f805f611f3c85856139ec565b50915091505f80611f4d6001613895565b9092509050611f7083611f6081876155e7565b611f6a908561560e565b83613f84565b979650505050505050565b611f836137d7565b63ffffffff82165f908152600c602052604090205460ff16611fc0576040516370abe85960e01b815263ffffffff83166004820152602401610eab565b826001600160a01b0316611fd383613808565b6001600160a01b031614611feb5782610ffd83613808565b63ffffffff82165f908152600d6020526040902054600160a01b900460ff161561203057604051630a42c0f960e41b815263ffffffff83166004820152602401610eab565b6298968063ffffffff8216111561205a57604051632e3a13e960e21b815260040160405180910390fd5b60408051606080820183526001825263ffffffff85811660208085018281528784168688018181526001600160a01b038c165f818152601486528a902098518954945192518816650100000000000268ffffffff000000000019939098166101000264ffffffff00199115159190911664ffffffffff19909516949094179390931716949094179095558551948552840152928201929092527f2682afad81f7b7a2141b8d3c671b3efc09ac3dac73f06a5cd8e4714ae8864c1b91015b60405180910390a1505050565b6008545f90600160c01b900460ff16156121505760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790555f8061216f6001613895565b9150915061217e858383613f90565b9250825f036121a057604051639768300560e01b815260040160405180910390fd5b6008546001600160c01b03166121b6868361560e565b11156121d55760405163adea3dfd60e01b815260040160405180910390fd5b600854612213907f000000000000000000000000000000000000000000000000000000000000000090600160e01b900463ffffffff16858888613f9c565b50506008805460ff60c01b1916905592915050565b60018054610ece9061559b565b61223d6137d7565b6122456139c1565b63ffffffff83165f908152600c602052604090205460ff16156122835760405163335894fb60e11b815263ffffffff84166004820152602401610eab565b63ffffffff83165f908152600e602052604090205460ff166122c057604051631f9db01d60e31b815263ffffffff84166004820152602401610eab565b6040516385ae5d5760e01b815263ffffffff841660048201525f90819081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906385ae5d57906024015f60405180830381865afa15801561232d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261235491908101906157b0565b9250925092508315158215151461238657604051632b1d0bd360e11b815263ffffffff87166004820152602401610eab565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600d9092529490208351815492511515600160a01b026001600160a81b0319909316931692909217178155915190919060018201906123ff908261588e565b5060608201516002820190612414908261588e565b50905050811561245557600b546020116124445760405163f025236d60e01b815260206004820152602401610eab565b612450600b8888614040565b612487565b600a5460201161247b5760405163f025236d60e01b815260206004820152602401610eab565b612487600a8888614040565b63ffffffff86165f908152600c602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb906124ea9088908a9063ffffffff92831681529116602082015260400190565b60405180910390a150505050505050565b6125036137d7565b5f8161254b57600a8463ffffffff1681548110612522576125226155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16612589565b600b8463ffffffff1681548110612564576125646155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90508063ffffffff168363ffffffff1614158061262d57506040516321a0f75360e01b815263ffffffff841660048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906321a0f75390602401602060405180830381865afa158015612609573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061262d9190615795565b1561264b5760405163d4db0b7960e01b815260040160405180910390fd5b611477848484613c58565b61265e6137d7565b600854600160d01b900460ff16612676576001612678565b5f5b60088054911515600160d01b0260ff60d01b19909216919091179055565b5f61269f613275565b600854600160c01b900460ff16156126c95760405162461bcd60e51b8152600401610eab90615577565b610ebd600161332c565b335f908152600360205260408120805483919083906126f39084906155e7565b90915550506001600160a01b0383165f81815260036020526040908190208054850190555133905f80516020615f35833981519152906111109086815260200190565b5f5b818110156127b6576127a3838383818110612755576127556155fa565b90506020028101906127679190615949565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525030939250506141fd9050565b50806127ae8161598b565b915050612738565b505050565b6127c36137d7565b6008546001600160c01b039081169082161015611c6a576040516334f1ec1b60e01b815260040160405180910390fd5b6127fb6137d7565b601154604080516001600160a01b03928316815291831660208301527f51dbb5a65bb22737861a63ec12ba6ce78a98631e9404b0567a2eaf7a06fc544d910160405180910390a1601180546001600160a01b0319166001600160a01b0392909216919091179055565b6008545f90600160d01b900460ff166128fd57604051630ad85dff60e41b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063ad85dff090602401602060405180830381865afa1580156128d9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ebd9190615795565b505f90565b5f805f61290f6001613895565b915091506110ae848383613f90565b6008545f90600160c01b900460ff161561294a5760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790555f8061296881613895565b915091506129778683836139b5565b925061298586848787614222565b50506008805460ff60c01b191690559392505050565b6129a36137d7565b670de0b6b3a76400006001600160401b03821611156129d557604051633d0203e560e01b815260040160405180910390fd5b601054604080516001600160401b03928316815291831660208301527fb5cc994a260a85a42d6588668221571ae0a14f0a28f9e4817a5195262102c868910160405180910390a16010805467ffffffffffffffff19166001600160401b0392909216919091179055565b6008545f90600160c01b900460ff1615612a6b5760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790555f80612a8981613895565b91509150612a988683836139a9565b9250825f03612aba57604051639768300560e01b815260040160405180910390fd5b61298583878787614222565b612ace6137d7565b5f808415612b13575f612adf610e78565b9050612afe612af0866127106159a3565b829061ffff166127106142f8565b9250612b0f612af0866127106159c5565b9150505b612b1e600284614316565b600980546001600160a01b0319166001600160a01b0385161790555f612b42610e78565b90508515612b865782811080612b5757508181115b15612b865760405163628cc47560e11b8152600481018290526024810184905260448101839052606401610eab565b505050505050565b6008545f90600160c81b900460ff1615612ba957505f919050565b6008546001600160c01b03166002600160c01b03198101612bcd57505f1992915050565b6002546001600160c01b038216811015612bf957612bf4816001600160c01b0384166155e7565b6110ae565b5f949350505050565b5f805f612c0f6001613895565b915091506110ae848383613f84565b6008545f90600160c01b900460ff1615612c4a5760405162461bcd60e51b8152600401610eab90615577565b61111c825f6143f4565b612c5c6137d7565b63ffffffff81165f818152600e60209081526040808320805460ff191690558051938452908301919091527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f91016111f3565b42841015612cff5760405162461bcd60e51b815260206004820152601760248201527f5045524d49545f444541444c494e455f455850495245440000000000000000006044820152606401610eab565b5f6001612d0a61147d565b6001600160a01b038a81165f8181526005602090815260409182902080546001810190915582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98184015280840194909452938d166060840152608083018c905260a083019390935260c08083018b90528151808403909101815260e08301909152805192019190912061190160f01b6101008301526101028201929092526101228101919091526101420160408051601f1981840301815282825280516020918201205f84529083018083525260ff871690820152606081018590526080810184905260a0016020604051602081039080840390855afa158015612e12573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b03811615801590612e485750876001600160a01b0316816001600160a01b0316145b612e855760405162461bcd60e51b815260206004820152600e60248201526d24a72b20a624a22fa9a4a3a722a960911b6044820152606401610eab565b6001600160a01b039081165f9081526004602090815260408083208a8516808552908352928190208990555188815291928a16917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a350505050505050565b6008545f90600160c01b900460ff1615612f195760405162461bcd60e51b8152600401610eab90615577565b61111c8260016143f4565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614612f6d57604051633cf941a360e01b815260040160405180910390fd5b600854600160d81b900460ff16612f97576040516304a246dd60e51b815260040160405180910390fd5b5f612fa4828401846159e0565b9050612faf81613dff565b5f5b86811015613060576130507f0000000000000000000000000000000000000000000000000000000000000000878784818110612fef57612fef6155fa565b905060200201358a8a85818110613008576130086155fa565b90506020020135613019919061560e565b8c8c8581811061302b5761302b6155fa565b90506020020160208101906130409190615088565b6001600160a01b0316919061446e565b6130598161598b565b9050612fb1565b50505050505050505050565b613081335f356001600160e01b0319166144e2565b61309d5760405162461bcd60e51b8152600401610eab90615a24565b600680546001600160a01b0319166001600160a01b03831690811790915560405133907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a350565b6130fd335f356001600160e01b0319166144e2565b6131195760405162461bcd60e51b8152600401610eab90615a24565b6131238282614316565b601260ff16816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613164573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131889190615a4a565b60ff161415806132095750306001600160a01b0316816001600160a01b031663d4b839926040518163ffffffff1660e01b8152600401602060405180830381865afa1580156131d9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131fd9190615a65565b6001600160a01b031614155b156132275760405163229e78bb60e01b815260040160405180910390fd5b601380546001600160a01b0319166001600160a01b0383169081179091556040519081527f51b1b17228af00bd72d43ecec4334e09b3584633abf6ef363a9fde05dfa73f8890602001611c26565b600854600160d01b900460ff1661332a57604051630ad85dff60e41b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063ad85dff090602401602060405180830381865afa1580156132e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061330c9190615795565b1561332a57604051630f301f8f60e41b815260040160405180910390fd5b565b600a545f9081816001600160401b0381111561334a5761334a614f3d565b604051908082528060200260200182016040528015613373578160200160208202803683370190505b5090505f826001600160401b0381111561338f5761338f614f3d565b6040519080825280602002602001820160405280156133b8578160200160208202803683370190505b509050841561351f575f5b83811015613484575f600a82815481106133df576133df6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16905061340e81614588565b838381518110613420576134206155fa565b60200260200101818152505f036134375750613474565b61344081613808565b848381518110613452576134526155fa565b60200260200101906001600160a01b031690816001600160a01b031681525050505b61347d8161598b565b90506133c3565b5060095460405163b333a17560e01b81526001600160a01b039091169063b333a175906134d990859085907f000000000000000000000000000000000000000000000000000000000000000090600401615af0565b602060405180830381865afa1580156134f4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135189190615b2d565b9350611963565b600b545f816001600160401b0381111561353b5761353b614f3d565b604051908082528060200260200182016040528015613564578160200160208202803683370190505b5090505f826001600160401b0381111561358057613580614f3d565b6040519080825280602002602001820160405280156135a9578160200160208202803683370190505b5090505f5b8681101561366f575f600a82815481106135ca576135ca6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690506135f981613bd2565b86838151811061360b5761360b6155fa565b60200260200101818152505f03613622575061365f565b61362b81613808565b87838151811061363d5761363d6155fa565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6136688161598b565b90506135ae565b505f5b83811015613733575f600b828154811061368e5761368e6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690506136bd81613bd2565b8383815181106136cf576136cf6155fa565b60200260200101818152505f036136e65750613723565b6136ef81613808565b848381518110613701576137016155fa565b60200260200101906001600160a01b031690816001600160a01b031681525050505b61372c8161598b565b9050613672565b50600954604051637563738b60e11b81526001600160a01b039091169063eac6e7169061378c9088908890879087907f000000000000000000000000000000000000000000000000000000000000000090600401615b44565b602060405180830381865afa1580156137a7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137cb9190615b2d565b98975050505050505050565b6137ec335f356001600160e01b0319166144e2565b61332a5760405162461bcd60e51b8152600401610eab90615a24565b63ffffffff81165f908152600d60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf9161384f9160010190600401615c24565b602060405180830381865afa15801561386a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061388e9190615a65565b9392505050565b6013545f9081906001600160a01b0316801561398a575f805f836001600160a01b031663c36af4606040518163ffffffff1660e01b8152600401606060405180830381865afa1580156138ea573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061390e9190615c36565b92509250925080156139335760405163229e78bb60e01b815260040160405180910390fd5b5f8715613950578284116139475782613949565b835b9050613962565b82841061395d578261395f565b835b90505b600254955061397f866139776012600a615d41565b8391906142f8565b9650505050506139a3565b60405163229e78bb60e01b815260040160405180910390fd5b50915091565b5f6110ae8484846142f8565b5f6110ae848385613dd2565b600854600160c81b900460ff161561332a576040516337a5332d60e11b815260040160405180910390fd5b6001600160a01b0382165f9081526014602090815260408083208151606081018352905460ff8116151580835263ffffffff610100830481169584019590955265010000000000909104909316918101919091528291829190613a625760405163217feaeb60e01b815260040160405180910390fd5b60095460405163151d4a5960e31b81526001600160a01b038881166004830152602482018890527f0000000000000000000000000000000000000000000000000000000000000000811660448301529091169063a8ea52c890606401602060405180830381865afa158015613ad9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613afd9190615b2d565b9350613b3181604001516305f5e100613b169190615d4f565b63ffffffff166305f5e100866142f89092919063ffffffff16565b925080602001519150509250925092565b5f805f613b4f6001613895565b9092509050613b6286611f60818a6155e7565b9250825f03613b845760405163426f153760e11b815260040160405180910390fd5b6008546001600160c01b0316613b9a848361560e565b1115613bb95760405163adea3dfd60e01b815260040160405180910390fd5b613bc689868a8688613f9c565b50509695505050505050565b63ffffffff81165f908152600d602052604080822080549151637841536560e01b81526001600160a01b03909216918291637841536591613c199160010190600401615c24565b602060405180830381865afa158015613c34573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061388e9190615b2d565b60085463ffffffff600160e01b909104811690831603613c8b576040516319ded73160e21b815260040160405180910390fd5b8015613ca157613c9c600b8461463d565b613cac565b613cac600a8461463d565b63ffffffff82165f908152600c60209081526040808320805460ff19169055600d909152812080546001600160a81b031916815590613cee6001830182614e06565b613cfb600283015f614e06565b50506040805163ffffffff8085168252851660208201527fa5cd0099b78b279c04987aa80ffffaf8fc8c8af4e7c7bce2686e8d01e2e1bd519101612117565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f604051613d6a9190615d6c565b6040805191829003822060208301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b828202811515841585830485141716613de9575f80fd5b6001826001830304018115150290509392505050565b5f5b8151811015613f80575f828281518110613e1d57613e1d6155fa565b602090810291909101810151516001600160a01b0381165f908152600f90925260409091205490915060ff16613e7157604051635df6b61760e11b81526001600160a01b0382166004820152602401610eab565b5f5b838381518110613e8557613e856155fa565b60200260200101516020015151811015613f6d57613eeb848481518110613eae57613eae6155fa565b6020026020010151602001518281518110613ecb57613ecb6155fa565b6020026020010151836001600160a01b03166141fd90919063ffffffff16565b507f7445c6598e1b553f076d507692eab3dceef0d608757141b53e9e56aa8bbaf48382858581518110613f2057613f206155fa565b6020026020010151602001518381518110613f3d57613f3d6155fa565b6020026020010151604051613f53929190615dde565b60405180910390a180613f658161598b565b915050613e73565b505080613f799061598b565b9050613e01565b5050565b5f6110ae8483856142f8565b5f6110ae848484613dd2565b613fc87f000000000000000000000000000000000000000000000000000000000000000084848461477c565b613fdd6001600160a01b03861633308661478c565b613fe7818361480b565b60408051848152602081018490526001600160a01b0383169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a361403984848484614862565b5050505050565b825480156141bd5783806140556001846155e7565b81548110614065576140656155fa565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a90920490931602179055906140c690836155e7565b90505b8363ffffffff1681111561416d57846140e36001836155e7565b815481106140f3576140f36155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16858281548110614129576141296155fa565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808061416590615e01565b9150506140c9565b5081848463ffffffff1681548110614187576141876155fa565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550611477565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b606061388e8383604051806060016040528060278152602001615f0e6027913961486c565b61422e84848484614784565b336001600160a01b03821614614299576001600160a01b0381165f9081526004602090815260408083203384529091529020545f1981146142975761427384826155e7565b6001600160a01b0383165f9081526004602090815260408083203384529091529020555b505b6142a381846148d6565b60408051858152602081018590526001600160a01b03808416929085169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a46114778483614935565b82820281151584158583048514171661430f575f80fd5b0492915050565b815f0361433657604051632db38d0560e01b815260040160405180910390fd5b806001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b93f9b0a846040518263ffffffff1660e01b815260040161438e91815260200190565b602060405180830381865afa1580156143a9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143cd9190615a65565b6001600160a01b031614613f8057604051634ee204d760e01b815260040160405180910390fd5b5f6143fd613275565b5f806144085f613895565b6001600160a01b0387165f90815260036020526040812054929450909250906144329084846139a9565b90505f61443f600161332c565b90508082111561444f5780614451565b815b9450851561446457611f70858585613f84565b5050505092915050565b5f60405163a9059cbb60e01b815283600482015282602482015260205f6044835f895af13d15601f3d1160015f5114161716915050806114775760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606401610eab565b6007545f906001600160a01b03168015801590614569575060405163b700961360e01b81526001600160a01b0382169063b70096139061452a90879030908890600401615768565b602060405180830381865afa158015614545573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906145699190615795565b806110ae57506006546001600160a01b03858116911614949350505050565b63ffffffff81165f908152600d6020526040812054600160a01b900460ff16156145b357505f919050565b63ffffffff82165f908152600d60205260409081902080549151637d2872e960e11b81526001600160a01b039092169163fa50e5d2916145fe91600182019160020190600401615e16565b602060405180830381865afa158015614619573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061111c9190615b2d565b815463ffffffff8216811161468a5760405162461bcd60e51b8152602060048201526013602482015272496e646578206f7574206f6620626f756e647360681b6044820152606401610eab565b63ffffffff82165b61469d6001836155e7565b81101561473a57836146b082600161560e565b815481106146c0576146c06155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff168482815481106146f6576146f66155fa565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff16021790555080806147329061598b565b915050614692565b508280548061474b5761474b615e43565b5f8281526020902060085f1990920191820401805463ffffffff600460078516026101000a02191690559055505050565b6147846139c1565b611477613275565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f5114161716915050806140395760405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606401610eab565b8060025f82825461481c919061560e565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481525f80516020615f3583398151915291015b60405180910390a35050565b6114778484614c8a565b60605f80856001600160a01b0316856040516148889190615e57565b5f60405180830381855af49150503d805f81146148c0576040519150601f19603f3d011682016040523d82523d5f602084013e6148c5565b606091505b509150915061195986838387614d16565b6001600160a01b0382165f90815260036020526040812080548392906148fd9084906155e7565b90915550506002805482900390556040518181525f906001600160a01b038416905f80516020615f3583398151915290602001614856565b61495c60405180608001604052805f81526020015f81526020015f81526020015f81525090565b600954604051630226614760e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015290911690630226614790602401602060405180830381865afa1580156149c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906149e89190615b2d565b6040820152614a187f0000000000000000000000000000000000000000000000000000000000000000600a615d41565b6060820152600a545f5b81811015614c67575f600a8281548110614a3e57614a3e6155fa565b5f9182526020822060088204015460079091166004026101000a900463ffffffff169150614a6b82614588565b9050805f03614a7b575050614c57565b5f614a8583613808565b600954604051630226614760e01b81526001600160a01b038084166004830152929350911690630226614790602401602060405180830381865afa158015614acf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614af39190615b2d565b865f018181525050806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015614b37573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614b5b9190615a4a565b614b6690600a615d41565b6020870181905286515f918291614b9091614b8987670de0b6b3a7640000615e72565b91906142f8565b9050614baf88606001518960400151836142f89092919063ffffffff16565b9150614bc3670de0b6b3a764000083615e89565b9150505f89821115614c26575f614bf189604001518a606001518d670de0b6b3a7640000614b899190615e72565b60208a01518a51919250614c07918391906142f8565b9150614c1b670de0b6b3a764000083615e89565b91505f9a5050614c35565b5082614c32828b6155e7565b99505b614c4085828b614d8e565b895f03614c51575050505050614c67565b50505050505b614c608161598b565b9050614a22565b5083156114775760405163cc5ea39b60e01b815260048101859052602401610eab565b63ffffffff82165f908152600d602052604090819020805491516001600160a01b0390921691611477916369445c3160e01b91614cd4918691600182019160020190602401615ea8565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526001600160a01b038316906141fd565b60608315614d845782515f03614d7d576001600160a01b0385163b614d7d5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610eab565b50816110ae565b6110ae8383614ddc565b63ffffffff83165f908152600d602052604090819020805491516001600160a01b03909216916140399163c9111bd760e01b91614cd491879187916001810191600290910190602401615ed2565b815115614dec5781518083602001fd5b8060405162461bcd60e51b8152600401610eab9190614ea5565b508054614e129061559b565b5f825580601f10614e21575050565b601f0160209004905f5260205f2090810190614e3d9190614e40565b50565b5b80821115614e54575f8155600101614e41565b5090565b5f5b83811015614e72578181015183820152602001614e5a565b50505f910152565b5f8151808452614e91816020860160208601614e58565b601f01601f19169290920160200192915050565b602081525f61388e6020830184614e7a565b803563ffffffff81168114614eca575f80fd5b919050565b5f60208284031215614edf575f80fd5b61388e82614eb7565b5f60208284031215614ef8575f80fd5b5035919050565b6001600160a01b0381168114614e3d575f80fd5b5f8060408385031215614f24575f80fd5b8235614f2f81614eff565b946020939093013593505050565b634e487b7160e01b5f52604160045260245ffd5b604080519081016001600160401b0381118282101715614f7357614f73614f3d565b60405290565b604051601f8201601f191681016001600160401b0381118282101715614fa157614fa1614f3d565b604052919050565b5f6001600160401b03821115614fc157614fc1614f3d565b50601f01601f191660200190565b5f82601f830112614fde575f80fd5b8135614ff1614fec82614fa9565b614f79565b818152846020838601011115615005575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f8060808587031215615034575f80fd5b843561503f81614eff565b9350602085013561504f81614eff565b92506040850135915060608501356001600160401b03811115615070575f80fd5b61507c87828801614fcf565b91505092959194509250565b5f60208284031215615098575f80fd5b813561388e81614eff565b5f805f606084860312156150b5575f80fd5b83356150c081614eff565b925060208401356150d081614eff565b929592945050506040919091013590565b5f805f606084860312156150f3575f80fd5b83356150fe81614eff565b925060208401359150604084013561511581614eff565b809150509250925092565b8015158114614e3d575f80fd5b5f806040838503121561513e575f80fd5b61514783614eb7565b9150602083013561515781615120565b809150509250929050565b5f805f60608486031215615174575f80fd5b61517d84614eb7565b925061518b60208501614eb7565b9150604084013561511581615120565b602080825282518282018190525f9190848201906040850190845b818110156151d857835163ffffffff16835292840192918401916001016151b6565b50909695505050505050565b5f8083601f8401126151f4575f80fd5b5081356001600160401b0381111561520a575f80fd5b6020830191508360208260051b8501011115615224575f80fd5b9250929050565b5f806020838503121561523c575f80fd5b82356001600160401b03811115615251575f80fd5b61525d858286016151e4565b90969095509350505050565b5f60208284031215615279575f80fd5b81356001600160c01b038116811461388e575f80fd5b5f80604083850312156152a0575f80fd5b82359150602083013561515781614eff565b5f805f606084860312156152c4575f80fd5b83356152cf81614eff565b92506152dd60208501614eb7565b91506152eb60408501614eb7565b90509250925092565b5f805f8060808587031215615307575f80fd5b61531085614eb7565b935061531e60208601614eb7565b925060408501356001600160401b03811115615338575f80fd5b61534487828801614fcf565b925050606085013561535581615120565b939692955090935050565b5f805f60608486031215615372575f80fd5b83359250602084013561538481614eff565b9150604084013561511581614eff565b5f602082840312156153a4575f80fd5b81356001600160401b038116811461388e575f80fd5b5f805f606084860312156153cc575f80fd5b83356153d781615120565b9250602084013561ffff81168114615384575f80fd5b60ff81168114614e3d575f80fd5b5f805f805f805f60e0888a031215615411575f80fd5b873561541c81614eff565b9650602088013561542c81614eff565b95506040880135945060608801359350608088013561544a816153ed565b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215615478575f80fd5b823561548381614eff565b9150602083013561515781614eff565b5f805f805f805f806080898b0312156154aa575f80fd5b88356001600160401b03808211156154c0575f80fd5b6154cc8c838d016151e4565b909a50985060208b01359150808211156154e4575f80fd5b6154f08c838d016151e4565b909850965060408b0135915080821115615508575f80fd5b6155148c838d016151e4565b909650945060608b013591508082111561552c575f80fd5b818b0191508b601f83011261553f575f80fd5b81358181111561554d575f80fd5b8c602082850101111561555e575f80fd5b6020830194508093505050509295985092959890939650565b6020808252600a90820152695245454e5452414e435960b01b604082015260600190565b600181811c908216806155af57607f821691505b6020821081036155cd57634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561111c5761111c6155d3565b634e487b7160e01b5f52603260045260245ffd5b8082018082111561111c5761111c6155d3565b5f6001600160401b0382111561563957615639614f3d565b5060051b60200190565b5f615650614fec84615621565b8381529050602080820190600585901b84018681111561566e575f80fd5b845b81811015615751576001600160401b03808235111561568d575f80fd5b813587016040818b0312156156a0575f80fd5b6156a8614f51565b6156b28235614eff565b8135815285820135838111156156c6575f80fd5b8083019250508a601f8301126156da575f80fd5b81356156e8614fec82615621565b81815260059190911b8301870190878101908d831115615706575f80fd5b8885015b8381101561573b57868135111561571f575f80fd5b61572e8f8b8335890101614fcf565b835291890191890161570a565b5083890152505086525050928201928201615670565b505050509392505050565b5f61388e368484615643565b6001600160a01b0393841681529190921660208201526001600160e01b0319909116604082015260600190565b5f602082840312156157a5575f80fd5b815161388e81615120565b5f805f606084860312156157c2575f80fd5b83516157cd81614eff565b60208501519093506157de81615120565b60408501519092506001600160401b038111156157f9575f80fd5b8401601f81018613615809575f80fd5b8051615817614fec82614fa9565b81815287602083850101111561582b575f80fd5b61583c826020830160208601614e58565b8093505050509250925092565b601f8211156127b6575f81815260208120601f850160051c8101602086101561586f5750805b601f850160051c820191505b81811015612b865782815560010161587b565b81516001600160401b038111156158a7576158a7614f3d565b6158bb816158b5845461559b565b84615849565b602080601f8311600181146158ee575f84156158d75750858301515b5f19600386901b1c1916600185901b178555612b86565b5f85815260208120601f198616915b8281101561591c578886015182559484019460019091019084016158fd565b508582101561593957878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f808335601e1984360301811261595e575f80fd5b8301803591506001600160401b03821115615977575f80fd5b602001915036819003821315615224575f80fd5b5f6001820161599c5761599c6155d3565b5060010190565b61ffff8281168282160390808211156159be576159be6155d3565b5092915050565b61ffff8181168382160190808211156159be576159be6155d3565b5f602082840312156159f0575f80fd5b81356001600160401b03811115615a05575f80fd5b8201601f81018413615a15575f80fd5b6110ae84823560208401615643565b6020808252600c908201526b15539055551213d49256915160a21b604082015260600190565b5f60208284031215615a5a575f80fd5b815161388e816153ed565b5f60208284031215615a75575f80fd5b815161388e81614eff565b5f8151808452602080850194508084015f5b83811015615ab75781516001600160a01b031687529582019590820190600101615a92565b509495945050505050565b5f8151808452602080850194508084015f5b83811015615ab757815187529582019590820190600101615ad4565b606081525f615b026060830186615a80565b8281036020840152615b148186615ac2565b91505060018060a01b0383166040830152949350505050565b5f60208284031215615b3d575f80fd5b5051919050565b60a081525f615b5660a0830188615a80565b8281036020840152615b688188615ac2565b90508281036040840152615b7c8187615a80565b90508281036060840152615b908186615ac2565b91505060018060a01b03831660808301529695505050505050565b5f8154615bb78161559b565b808552602060018381168015615bd45760018114615bee57615c19565b60ff1985168884015283151560051b880183019550615c19565b865f52825f205f5b85811015615c115781548a8201860152908301908401615bf6565b890184019650505b505050505092915050565b602081525f61388e6020830184615bab565b5f805f60608486031215615c48575f80fd5b8351925060208401519150604084015161511581615120565b600181815b80851115615c9b57815f1904821115615c8157615c816155d3565b80851615615c8e57918102915b93841c9390800290615c66565b509250929050565b5f82615cb15750600161111c565b81615cbd57505f61111c565b8160018114615cd35760028114615cdd57615cf9565b600191505061111c565b60ff841115615cee57615cee6155d3565b50506001821b61111c565b5060208310610133831016604e8410600b8410161715615d1c575081810a61111c565b615d268383615c61565b805f1904821115615d3957615d396155d3565b029392505050565b5f61388e60ff841683615ca3565b63ffffffff8281168282160390808211156159be576159be6155d3565b5f808354615d798161559b565b60018281168015615d915760018114615da657615dd2565b60ff1984168752821515830287019450615dd2565b875f526020805f205f5b85811015615dc95781548a820152908401908201615db0565b50505082870194505b50929695505050505050565b6001600160a01b03831681526040602082018190525f906110ae90830184614e7a565b5f81615e0f57615e0f6155d3565b505f190190565b604081525f615e286040830185615bab565b8281036020840152615e3a8185615bab565b95945050505050565b634e487b7160e01b5f52603160045260245ffd5b5f8251615e68818460208701614e58565b9190910192915050565b808202811582820484141761111c5761111c6155d3565b5f82615ea357634e487b7160e01b5f52601260045260245ffd5b500490565b838152606060208201525f615ec06060830185615bab565b82810360408401526119598185615bab565b8481526001600160a01b03841660208201526080604082018190525f90615efb90830185615bab565b8281036060840152611f708185615bab56fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa264697066735822122001ee3b7a5e5b203fe12552069e6757861290b0f372c1673e65521345b9de750b64736f6c634300081500338be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c65640000000000000000000000002322ba43eff1542b6a7baed35e66099ea0d12bd100000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000005af3107a400000000000000000000000000000000000000000000000000006f05b59d3b200000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8000000000000000000000000000000000000000000000000000000000000001045746865722e66692d4c69717569643100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b4c5149444554484649563100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000001
Deployed Bytecode
0x60806040526004361061042f575f3560e01c8063855bccb31161022b578063ba08765211610129578063d446bbcc116100b3578063e753e60011610078578063e753e60014610d9a578063ef8b30f714610c53578063f04f270714610e1b578063f2fde38b14610e3a578063f5743bc914610e59575f80fd5b8063d446bbcc14610cd0578063d505accf14610d07578063d7d4bf4514610d26578063d905777e14610d45578063dd62ed3e14610d64575f80fd5b8063c63d75b6116100f9578063c63d75b614610c34578063c6e6f59214610c53578063ce96cb7714610c72578063cf30901214610c91578063d1e8840414610cb1575f80fd5b8063ba08765214610bb7578063bf7e214f14610bd6578063bf86d69014610bf5578063c588d8d614610c15575f80fd5b8063a373e3ff116101b5578063b0a75d361161017a578063b0a75d3614610b27578063b187bd2614610b46578063b3d7f6b914610b5a578063b460af9414610b79578063b5292a9914610b98575f80fd5b8063a373e3ff14610aa2578063a8144e4814610ab6578063a9059cbb14610aca578063ac9650d814610ae9578063b0646e2714610b08575f80fd5b806395d89b41116101fb57806395d89b41146109f85780639955a9d414610a0c5780639959af9414610a2b5780639c5f00c214610a4b578063a07bee0b14610a83575f80fd5b8063855bccb31461096d5780638da5cb5b1461098c57806393bbeac0146109ab57806394bf804d146109d9575f80fd5b80633d8ab1e5116103385780635e2c576e116102c257806371e99dc21161028757806371e99dc2146108bd5780637a9e5e4b146108d15780637ab92915146108f05780637b1039991461090f5780637ecebe0014610942575f80fd5b80635e2c576e146107d55780635f6b88a0146107e95780636419111e146108085780636e553f651461087357806370a0823114610892575f80fd5b80634cdad506116103085780634cdad506146104a35780634e84befe14610759578063501eb4fe14610778578063530a371414610797578063575bbce6146107b6575f80fd5b80633d8ab1e5146106da5780633e3382ba146106f9578063402d267d1461071a5780634c4602da14610739575f80fd5b8063196e8285116103b9578063313ce56711610389578063313ce5671461061057806333e15be2146106555780633644e51514610674578063379e0b131461068857806338d52e0f146106a7575f80fd5b8063196e82851461057c578063217bb34d146105b357806323b872dd146105d25780632b91c5de146105f1575f80fd5b8063095ea7b3116103ff578063095ea7b3146104c25780630a28a477146104f15780630a680e1814610510578063150b7a021461052457806318160ddd14610567575f80fd5b806301e1d1141461043a57806306fdde03146104615780630780fd3a1461048257806307a2d13a146104a3575f80fd5b3661043657005b5f80fd5b348015610445575f80fd5b5061044e610e78565b6040519081526020015b60405180910390f35b34801561046c575f80fd5b50610475610ec2565b6040516104589190614ea5565b34801561048d575f80fd5b506104a161049c366004614ecf565b610f4d565b005b3480156104ae575f80fd5b5061044e6104bd366004614ee8565b611093565b3480156104cd575f80fd5b506104e16104dc366004614f13565b6110b6565b6040519015158152602001610458565b3480156104fc575f80fd5b5061044e61050b366004614ee8565b611122565b34801561051b575f80fd5b506104a161113d565b34801561052f575f80fd5b5061054e61053e366004615021565b630a85bd0160e11b949350505050565b6040516001600160e01b03199091168152602001610458565b348015610572575f80fd5b5061044e60025481565b348015610587575f80fd5b5060135461059b906001600160a01b031681565b6040516001600160a01b039091168152602001610458565b3480156105be575f80fd5b506104a16105cd366004615088565b611197565b3480156105dd575f80fd5b506104e16105ec3660046150a3565b6111fe565b3480156105fc575f80fd5b5061044e61060b3660046150e1565b6112d8565b34801561061b575f80fd5b506106437f000000000000000000000000000000000000000000000000000000000000001281565b60405160ff9091168152602001610458565b348015610660575f80fd5b506104a161066f36600461512d565b6113a2565b34801561067f575f80fd5b5061044e61147d565b348015610693575f80fd5b506104a16106a2366004615162565b6114d2565b3480156106b2575f80fd5b5061059b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b3480156106e5575f80fd5b506104a16106f4366004615088565b611777565b348015610704575f80fd5b5061070d61184e565b604051610458919061519b565b348015610725575f80fd5b5061044e610734366004615088565b6118cf565b348015610744575f80fd5b506008546104e190600160d81b900460ff1681565b348015610764575f80fd5b506104a161077336600461522b565b61196b565b348015610783575f80fd5b506104a1610792366004614ecf565b611ad2565b3480156107a2575f80fd5b506104a16107b1366004614ee8565b611baa565b3480156107c1575f80fd5b506104a16107d0366004615269565b611c32565b3480156107e0575f80fd5b506104a1611c8c565b3480156107f4575f80fd5b506104a1610803366004615088565b611cfb565b348015610813575f80fd5b5061084f610822366004615088565b60146020525f908152604090205460ff81169063ffffffff61010082048116916501000000000090041683565b60408051931515845263ffffffff9283166020850152911690820152606001610458565b34801561087e575f80fd5b5061044e61088d36600461528f565b611d59565b34801561089d575f80fd5b5061044e6108ac366004615088565b60036020525f908152604090205481565b3480156108c8575f80fd5b5061070d611dee565b3480156108dc575f80fd5b506104a16108eb366004615088565b611e4a565b3480156108fb575f80fd5b5061044e61090a366004614f13565b611f2f565b34801561091a575f80fd5b5061059b7f00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd81565b34801561094d575f80fd5b5061044e61095c366004615088565b60056020525f908152604090205481565b348015610978575f80fd5b506104a16109873660046152b2565b611f7b565b348015610997575f80fd5b5060065461059b906001600160a01b031681565b3480156109b6575f80fd5b506104e16109c5366004614ee8565b600c6020525f908152604090205460ff1681565b3480156109e4575f80fd5b5061044e6109f336600461528f565b612124565b348015610a03575f80fd5b50610475612228565b348015610a17575f80fd5b506104a1610a263660046152f4565b612235565b348015610a36575f80fd5b506008546104e190600160d01b900460ff1681565b348015610a56575f80fd5b50600854610a6e90600160e01b900463ffffffff1681565b60405163ffffffff9091168152602001610458565b348015610a8e575f80fd5b506104a1610a9d366004615162565b6124fb565b348015610aad575f80fd5b506104a1612656565b348015610ac1575f80fd5b5061044e612696565b348015610ad5575f80fd5b506104e1610ae4366004614f13565b6126d3565b348015610af4575f80fd5b506104a1610b0336600461522b565b612736565b348015610b13575f80fd5b506104a1610b22366004615269565b6127bb565b348015610b32575f80fd5b506104a1610b41366004615088565b6127f3565b348015610b51575f80fd5b506104e1612864565b348015610b65575f80fd5b5061044e610b74366004614ee8565b612902565b348015610b84575f80fd5b5061044e610b93366004615360565b61291e565b348015610ba3575f80fd5b506104a1610bb2366004615394565b61299b565b348015610bc2575f80fd5b5061044e610bd1366004615360565b612a3f565b348015610be1575f80fd5b5060075461059b906001600160a01b031681565b348015610c00575f80fd5b506008546104e190600160c81b900460ff1681565b348015610c20575f80fd5b506104a1610c2f3660046153ba565b612ac6565b348015610c3f575f80fd5b5061044e610c4e366004615088565b612b8e565b348015610c5e575f80fd5b5061044e610c6d366004614ee8565b612c02565b348015610c7d575f80fd5b5061044e610c8c366004615088565b612c1e565b348015610c9c575f80fd5b506008546104e190600160c01b900460ff1681565b348015610cbc575f80fd5b506104a1610ccb366004614ecf565b612c54565b348015610cdb575f80fd5b50600854610cef906001600160c01b031681565b6040516001600160c01b039091168152602001610458565b348015610d12575f80fd5b506104a1610d213660046153fb565b612caf565b348015610d31575f80fd5b5060095461059b906001600160a01b031681565b348015610d50575f80fd5b5061044e610d5f366004615088565b612eed565b348015610d6f575f80fd5b5061044e610d7e366004615467565b600460209081525f928352604080842090915290825290205481565b348015610da5575f80fd5b50601054601154610de2916001600160401b0380821692680100000000000000008304821692600160801b9004909116906001600160a01b031684565b604080516001600160401b039586168152938516602085015291909316908201526001600160a01b039091166060820152608001610458565b348015610e26575f80fd5b506104a1610e35366004615493565b612f24565b348015610e45575f80fd5b506104a1610e54366004615088565b61306c565b348015610e64575f80fd5b506104a1610e7336600461528f565b6130e8565b5f610e81613275565b600854600160c01b900460ff1615610eb45760405162461bcd60e51b8152600401610eab90615577565b60405180910390fd5b610ebd5f61332c565b905090565b5f8054610ece9061559b565b80601f0160208091040260200160405190810160405280929190818152602001828054610efa9061559b565b8015610f455780601f10610f1c57610100808354040283529160200191610f45565b820191905f5260205f20905b815481529060010190602001808311610f2857829003601f168201915b505050505081565b610f556137d7565b63ffffffff81165f908152600c602052604090205460ff16610f92576040516370abe85960e01b815263ffffffff82166004820152602401610eab565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316610fc582613808565b6001600160a01b031614611029577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2610ffd82613808565b60405163298473c760e11b81526001600160a01b03928316600482015291166024820152604401610eab565b63ffffffff81165f908152600d6020526040902054600160a01b900460ff161561106e57604051630a42c0f960e41b815263ffffffff82166004820152602401610eab565b6008805463ffffffff909216600160e01b026001600160e01b03909216919091179055565b5f805f61109f5f613895565b915091506110ae8483836139a9565b949350505050565b335f8181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906111109086815260200190565b60405180910390a35060015b92915050565b5f805f61112e5f613895565b915091506110ae8483836139b5565b6111456137d7565b61114d6139c1565b6008805460ff60c81b1916600160c81b179055604051600181527fb8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3c906020015b60405180910390a1565b61119f6137d7565b6001600160a01b0381165f81815260146020908152604091829020805468ffffffffffffffffff1916905590519182527f741bf5c2d606526029e0f199a3ddf6c7ebafa7edb2e1405174105f458195e67991015b60405180910390a150565b6001600160a01b0383165f9081526004602090815260408083203384529091528120545f1981146112575761123383826155e7565b6001600160a01b0386165f9081526004602090815260408083203384529091529020555b6001600160a01b0385165f908152600360205260408120805485929061127e9084906155e7565b90915550506001600160a01b038085165f81815260036020526040908190208054870190555190918716905f80516020615f35833981519152906112c59087815260200190565b60405180910390a3506001949350505050565b6008545f90600160c01b900460ff16156113045760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790555f808061132487876139ec565b92509250925061133887878585858a613b42565b604080516001600160a01b038a81168252602082018a905291810183905291955086169033907f385ba312edecbeeae57aca70f4fde3d83578697795291e74b1b4edb37d7291bf9060600160405180910390a350506008805460ff60c01b19169055509392505050565b6113aa6137d7565b5f816113f257600a8363ffffffff16815481106113c9576113c96155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16611430565b600b8363ffffffff168154811061140b5761140b6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90505f61143c82613bd2565b9050801561146c57604051631c7b946d60e31b815263ffffffff8316600482015260248101829052604401610eab565b611477848385613c58565b50505050565b5f7f000000000000000000000000000000000000000000000000000000000000000146146114ad57610ebd613d3a565b507f3959e56230166632a285ba1eca657e0bb21e45b2bd570705d743c85fb04bb17490565b6114da6137d7565b5f80821561160357600b8463ffffffff16815481106114fb576114fb6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169150600b8563ffffffff168154811061153a5761153a6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690508181600b8763ffffffff168154811061157b5761157b6155fa565b905f5260205f209060089182820401919006600402600b8863ffffffff16815481106115a9576115a96155fa565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff1602179055505050611720565b600a8463ffffffff168154811061161c5761161c6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169150600a8563ffffffff168154811061165b5761165b6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690508181600a8763ffffffff168154811061169c5761169c6155fa565b905f5260205f209060089182820401919006600402600a8863ffffffff16815481106116ca576116ca6155fa565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff16021790555050505b6040805163ffffffff84811682528381166020830152878116828401528616606082015290517fb7c5df04749a3a06a9a7bf1a8142ccf2a4ee6cbf4709489e876a6e4eb3301e8a9181900360800190a15050505050565b61177f6137d7565b604051636777140560e11b81526001600160a01b0382811660048301527f00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd169063ceee280a906024015f6040518083038186803b1580156117de575f80fd5b505afa1580156117f0573d5f803e3d5ffd5b505050506001600160a01b0381165f818152600f6020908152604091829020805460ff191660019081179091558251938452908301527f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7a91016111f3565b6060600b8054806020026020016040519081016040528092919081815260200182805480156118c557602002820191905f5260205f20905f905b82829054906101000a900463ffffffff1663ffffffff16815260200190600401906020826003010492830192600103820291508084116118885790505b5050505050905090565b6008545f90600160c81b900460ff16156118ea57505f919050565b6008546001600160c01b03166002600160c01b0319810161190e57505f1992915050565b5f8061191a6001613895565b91509150826001600160c01b0316811061193857505f949350505050565b5f61194c826001600160c01b0386166155e7565b90506119598184846139a9565b9695505050505050565b505050919050565b600854600160c01b900460ff16156119955760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790556119b06137d7565b6119b86139c1565b6119c0613275565b6008805460ff60d81b1916600160d81b1790555f8080806119e08161332c565b9050611a0b601254670de0b6b3a76400006119fb91906155e7565b8290670de0b6b3a7640000613dd2565b9350611a26601254670de0b6b3a76400006119fb919061560e565b6002549093509150611a429050611a3d858761575c565b613dff565b5f611a4c5f61332c565b905083811080611a5b57508281115b15611a8a5760405163628cc47560e11b8152600481018290526024810185905260448101849052606401610eab565b6002548214611aba57600254604051632b40145960e21b8152600481019190915260248101839052604401610eab565b50506008805463ff0000ff60c01b1916905550505050565b611ada6137d7565b604051635159d87f60e11b815263ffffffff821660048201527f00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd6001600160a01b03169063a2b3b0fe906024015f6040518083038186803b158015611b3d575f80fd5b505afa158015611b4f573d5f803e3d5ffd5b5050505063ffffffff81165f818152600e6020908152604091829020805460ff191660019081179091558251938452908301527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f91016111f3565b611bb26137d7565b67016345785d8a0000811115611bec576040516302d2a90f60e51b81526004810182905267016345785d8a00006024820152604401610eab565b601280549082905560408051828152602081018490527fdf4be33b2e9e3dd4d9e0e85645aea428494a0644a72c51d6a15aedae6b66a3ff91015b60405180910390a15050565b611c3a6137d7565b6008546001600160c01b039081169082161115611c6a576040516334f1ec1b60e01b815260040160405180910390fd5b600880546001600160c01b0319166001600160c01b0392909216919091179055565b611c946137d7565b600854600160c81b900460ff16611cbe5760405163ec7165bf60e01b815260040160405180910390fd5b6008805460ff60c81b191690556040515f81527fb8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3c9060200161118d565b611d036137d7565b6001600160a01b0381165f818152600f60209081526040808320805460ff191690558051938452908301919091527f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7a91016111f3565b6008545f90600160c01b900460ff1615611d855760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790819055611dda907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29085908190819063ffffffff600160e01b9091041687613b42565b6008805460ff60c01b191690559392505050565b6060600a8054806020026020016040519081016040528092919081815260200182805480156118c5575f918252602091829020805463ffffffff1684529082028301929091600491018084116118885790505050505050905090565b6006546001600160a01b0316331480611edc575060075460405163b700961360e01b81526001600160a01b039091169063b700961390611e9d90339030906001600160e01b03195f351690600401615768565b602060405180830381865afa158015611eb8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611edc9190615795565b611ee4575f80fd5b600780546001600160a01b0319166001600160a01b03831690811790915560405133907fa3396fd7f6e0a21b50e5089d2da70d5ac0a3bbbd1f617a93f134b76389980198905f90a350565b5f805f611f3c85856139ec565b50915091505f80611f4d6001613895565b9092509050611f7083611f6081876155e7565b611f6a908561560e565b83613f84565b979650505050505050565b611f836137d7565b63ffffffff82165f908152600c602052604090205460ff16611fc0576040516370abe85960e01b815263ffffffff83166004820152602401610eab565b826001600160a01b0316611fd383613808565b6001600160a01b031614611feb5782610ffd83613808565b63ffffffff82165f908152600d6020526040902054600160a01b900460ff161561203057604051630a42c0f960e41b815263ffffffff83166004820152602401610eab565b6298968063ffffffff8216111561205a57604051632e3a13e960e21b815260040160405180910390fd5b60408051606080820183526001825263ffffffff85811660208085018281528784168688018181526001600160a01b038c165f818152601486528a902098518954945192518816650100000000000268ffffffff000000000019939098166101000264ffffffff00199115159190911664ffffffffff19909516949094179390931716949094179095558551948552840152928201929092527f2682afad81f7b7a2141b8d3c671b3efc09ac3dac73f06a5cd8e4714ae8864c1b91015b60405180910390a1505050565b6008545f90600160c01b900460ff16156121505760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790555f8061216f6001613895565b9150915061217e858383613f90565b9250825f036121a057604051639768300560e01b815260040160405180910390fd5b6008546001600160c01b03166121b6868361560e565b11156121d55760405163adea3dfd60e01b815260040160405180910390fd5b600854612213907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290600160e01b900463ffffffff16858888613f9c565b50506008805460ff60c01b1916905592915050565b60018054610ece9061559b565b61223d6137d7565b6122456139c1565b63ffffffff83165f908152600c602052604090205460ff16156122835760405163335894fb60e11b815263ffffffff84166004820152602401610eab565b63ffffffff83165f908152600e602052604090205460ff166122c057604051631f9db01d60e31b815263ffffffff84166004820152602401610eab565b6040516385ae5d5760e01b815263ffffffff841660048201525f90819081906001600160a01b037f00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd16906385ae5d57906024015f60405180830381865afa15801561232d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261235491908101906157b0565b9250925092508315158215151461238657604051632b1d0bd360e11b815263ffffffff87166004820152602401610eab565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600d9092529490208351815492511515600160a01b026001600160a81b0319909316931692909217178155915190919060018201906123ff908261588e565b5060608201516002820190612414908261588e565b50905050811561245557600b546020116124445760405163f025236d60e01b815260206004820152602401610eab565b612450600b8888614040565b612487565b600a5460201161247b5760405163f025236d60e01b815260206004820152602401610eab565b612487600a8888614040565b63ffffffff86165f908152600c602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb906124ea9088908a9063ffffffff92831681529116602082015260400190565b60405180910390a150505050505050565b6125036137d7565b5f8161254b57600a8463ffffffff1681548110612522576125226155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16612589565b600b8463ffffffff1681548110612564576125646155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90508063ffffffff168363ffffffff1614158061262d57506040516321a0f75360e01b815263ffffffff841660048201527f00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd6001600160a01b0316906321a0f75390602401602060405180830381865afa158015612609573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061262d9190615795565b1561264b5760405163d4db0b7960e01b815260040160405180910390fd5b611477848484613c58565b61265e6137d7565b600854600160d01b900460ff16612676576001612678565b5f5b60088054911515600160d01b0260ff60d01b19909216919091179055565b5f61269f613275565b600854600160c01b900460ff16156126c95760405162461bcd60e51b8152600401610eab90615577565b610ebd600161332c565b335f908152600360205260408120805483919083906126f39084906155e7565b90915550506001600160a01b0383165f81815260036020526040908190208054850190555133905f80516020615f35833981519152906111109086815260200190565b5f5b818110156127b6576127a3838383818110612755576127556155fa565b90506020028101906127679190615949565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525030939250506141fd9050565b50806127ae8161598b565b915050612738565b505050565b6127c36137d7565b6008546001600160c01b039081169082161015611c6a576040516334f1ec1b60e01b815260040160405180910390fd5b6127fb6137d7565b601154604080516001600160a01b03928316815291831660208301527f51dbb5a65bb22737861a63ec12ba6ce78a98631e9404b0567a2eaf7a06fc544d910160405180910390a1601180546001600160a01b0319166001600160a01b0392909216919091179055565b6008545f90600160d01b900460ff166128fd57604051630ad85dff60e41b81523060048201527f00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd6001600160a01b03169063ad85dff090602401602060405180830381865afa1580156128d9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ebd9190615795565b505f90565b5f805f61290f6001613895565b915091506110ae848383613f90565b6008545f90600160c01b900460ff161561294a5760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790555f8061296881613895565b915091506129778683836139b5565b925061298586848787614222565b50506008805460ff60c01b191690559392505050565b6129a36137d7565b670de0b6b3a76400006001600160401b03821611156129d557604051633d0203e560e01b815260040160405180910390fd5b601054604080516001600160401b03928316815291831660208301527fb5cc994a260a85a42d6588668221571ae0a14f0a28f9e4817a5195262102c868910160405180910390a16010805467ffffffffffffffff19166001600160401b0392909216919091179055565b6008545f90600160c01b900460ff1615612a6b5760405162461bcd60e51b8152600401610eab90615577565b6008805460ff60c01b1916600160c01b1790555f80612a8981613895565b91509150612a988683836139a9565b9250825f03612aba57604051639768300560e01b815260040160405180910390fd5b61298583878787614222565b612ace6137d7565b5f808415612b13575f612adf610e78565b9050612afe612af0866127106159a3565b829061ffff166127106142f8565b9250612b0f612af0866127106159c5565b9150505b612b1e600284614316565b600980546001600160a01b0319166001600160a01b0385161790555f612b42610e78565b90508515612b865782811080612b5757508181115b15612b865760405163628cc47560e11b8152600481018290526024810184905260448101839052606401610eab565b505050505050565b6008545f90600160c81b900460ff1615612ba957505f919050565b6008546001600160c01b03166002600160c01b03198101612bcd57505f1992915050565b6002546001600160c01b038216811015612bf957612bf4816001600160c01b0384166155e7565b6110ae565b5f949350505050565b5f805f612c0f6001613895565b915091506110ae848383613f84565b6008545f90600160c01b900460ff1615612c4a5760405162461bcd60e51b8152600401610eab90615577565b61111c825f6143f4565b612c5c6137d7565b63ffffffff81165f818152600e60209081526040808320805460ff191690558051938452908301919091527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f91016111f3565b42841015612cff5760405162461bcd60e51b815260206004820152601760248201527f5045524d49545f444541444c494e455f455850495245440000000000000000006044820152606401610eab565b5f6001612d0a61147d565b6001600160a01b038a81165f8181526005602090815260409182902080546001810190915582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98184015280840194909452938d166060840152608083018c905260a083019390935260c08083018b90528151808403909101815260e08301909152805192019190912061190160f01b6101008301526101028201929092526101228101919091526101420160408051601f1981840301815282825280516020918201205f84529083018083525260ff871690820152606081018590526080810184905260a0016020604051602081039080840390855afa158015612e12573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b03811615801590612e485750876001600160a01b0316816001600160a01b0316145b612e855760405162461bcd60e51b815260206004820152600e60248201526d24a72b20a624a22fa9a4a3a722a960911b6044820152606401610eab565b6001600160a01b039081165f9081526004602090815260408083208a8516808552908352928190208990555188815291928a16917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a350505050505050565b6008545f90600160c01b900460ff1615612f195760405162461bcd60e51b8152600401610eab90615577565b61111c8260016143f4565b336001600160a01b037f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c81614612f6d57604051633cf941a360e01b815260040160405180910390fd5b600854600160d81b900460ff16612f97576040516304a246dd60e51b815260040160405180910390fd5b5f612fa4828401846159e0565b9050612faf81613dff565b5f5b86811015613060576130507f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8878784818110612fef57612fef6155fa565b905060200201358a8a85818110613008576130086155fa565b90506020020135613019919061560e565b8c8c8581811061302b5761302b6155fa565b90506020020160208101906130409190615088565b6001600160a01b0316919061446e565b6130598161598b565b9050612fb1565b50505050505050505050565b613081335f356001600160e01b0319166144e2565b61309d5760405162461bcd60e51b8152600401610eab90615a24565b600680546001600160a01b0319166001600160a01b03831690811790915560405133907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a350565b6130fd335f356001600160e01b0319166144e2565b6131195760405162461bcd60e51b8152600401610eab90615a24565b6131238282614316565b601260ff16816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613164573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131889190615a4a565b60ff161415806132095750306001600160a01b0316816001600160a01b031663d4b839926040518163ffffffff1660e01b8152600401602060405180830381865afa1580156131d9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131fd9190615a65565b6001600160a01b031614155b156132275760405163229e78bb60e01b815260040160405180910390fd5b601380546001600160a01b0319166001600160a01b0383169081179091556040519081527f51b1b17228af00bd72d43ecec4334e09b3584633abf6ef363a9fde05dfa73f8890602001611c26565b600854600160d01b900460ff1661332a57604051630ad85dff60e41b81523060048201527f00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd6001600160a01b03169063ad85dff090602401602060405180830381865afa1580156132e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061330c9190615795565b1561332a57604051630f301f8f60e41b815260040160405180910390fd5b565b600a545f9081816001600160401b0381111561334a5761334a614f3d565b604051908082528060200260200182016040528015613373578160200160208202803683370190505b5090505f826001600160401b0381111561338f5761338f614f3d565b6040519080825280602002602001820160405280156133b8578160200160208202803683370190505b509050841561351f575f5b83811015613484575f600a82815481106133df576133df6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16905061340e81614588565b838381518110613420576134206155fa565b60200260200101818152505f036134375750613474565b61344081613808565b848381518110613452576134526155fa565b60200260200101906001600160a01b031690816001600160a01b031681525050505b61347d8161598b565b90506133c3565b5060095460405163b333a17560e01b81526001600160a01b039091169063b333a175906134d990859085907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290600401615af0565b602060405180830381865afa1580156134f4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135189190615b2d565b9350611963565b600b545f816001600160401b0381111561353b5761353b614f3d565b604051908082528060200260200182016040528015613564578160200160208202803683370190505b5090505f826001600160401b0381111561358057613580614f3d565b6040519080825280602002602001820160405280156135a9578160200160208202803683370190505b5090505f5b8681101561366f575f600a82815481106135ca576135ca6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690506135f981613bd2565b86838151811061360b5761360b6155fa565b60200260200101818152505f03613622575061365f565b61362b81613808565b87838151811061363d5761363d6155fa565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6136688161598b565b90506135ae565b505f5b83811015613733575f600b828154811061368e5761368e6155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690506136bd81613bd2565b8383815181106136cf576136cf6155fa565b60200260200101818152505f036136e65750613723565b6136ef81613808565b848381518110613701576137016155fa565b60200260200101906001600160a01b031690816001600160a01b031681525050505b61372c8161598b565b9050613672565b50600954604051637563738b60e11b81526001600160a01b039091169063eac6e7169061378c9088908890879087907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290600401615b44565b602060405180830381865afa1580156137a7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137cb9190615b2d565b98975050505050505050565b6137ec335f356001600160e01b0319166144e2565b61332a5760405162461bcd60e51b8152600401610eab90615a24565b63ffffffff81165f908152600d60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf9161384f9160010190600401615c24565b602060405180830381865afa15801561386a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061388e9190615a65565b9392505050565b6013545f9081906001600160a01b0316801561398a575f805f836001600160a01b031663c36af4606040518163ffffffff1660e01b8152600401606060405180830381865afa1580156138ea573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061390e9190615c36565b92509250925080156139335760405163229e78bb60e01b815260040160405180910390fd5b5f8715613950578284116139475782613949565b835b9050613962565b82841061395d578261395f565b835b90505b600254955061397f866139776012600a615d41565b8391906142f8565b9650505050506139a3565b60405163229e78bb60e01b815260040160405180910390fd5b50915091565b5f6110ae8484846142f8565b5f6110ae848385613dd2565b600854600160c81b900460ff161561332a576040516337a5332d60e11b815260040160405180910390fd5b6001600160a01b0382165f9081526014602090815260408083208151606081018352905460ff8116151580835263ffffffff610100830481169584019590955265010000000000909104909316918101919091528291829190613a625760405163217feaeb60e01b815260040160405180910390fd5b60095460405163151d4a5960e31b81526001600160a01b038881166004830152602482018890527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2811660448301529091169063a8ea52c890606401602060405180830381865afa158015613ad9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613afd9190615b2d565b9350613b3181604001516305f5e100613b169190615d4f565b63ffffffff166305f5e100866142f89092919063ffffffff16565b925080602001519150509250925092565b5f805f613b4f6001613895565b9092509050613b6286611f60818a6155e7565b9250825f03613b845760405163426f153760e11b815260040160405180910390fd5b6008546001600160c01b0316613b9a848361560e565b1115613bb95760405163adea3dfd60e01b815260040160405180910390fd5b613bc689868a8688613f9c565b50509695505050505050565b63ffffffff81165f908152600d602052604080822080549151637841536560e01b81526001600160a01b03909216918291637841536591613c199160010190600401615c24565b602060405180830381865afa158015613c34573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061388e9190615b2d565b60085463ffffffff600160e01b909104811690831603613c8b576040516319ded73160e21b815260040160405180910390fd5b8015613ca157613c9c600b8461463d565b613cac565b613cac600a8461463d565b63ffffffff82165f908152600c60209081526040808320805460ff19169055600d909152812080546001600160a81b031916815590613cee6001830182614e06565b613cfb600283015f614e06565b50506040805163ffffffff8085168252851660208201527fa5cd0099b78b279c04987aa80ffffaf8fc8c8af4e7c7bce2686e8d01e2e1bd519101612117565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f604051613d6a9190615d6c565b6040805191829003822060208301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b828202811515841585830485141716613de9575f80fd5b6001826001830304018115150290509392505050565b5f5b8151811015613f80575f828281518110613e1d57613e1d6155fa565b602090810291909101810151516001600160a01b0381165f908152600f90925260409091205490915060ff16613e7157604051635df6b61760e11b81526001600160a01b0382166004820152602401610eab565b5f5b838381518110613e8557613e856155fa565b60200260200101516020015151811015613f6d57613eeb848481518110613eae57613eae6155fa565b6020026020010151602001518281518110613ecb57613ecb6155fa565b6020026020010151836001600160a01b03166141fd90919063ffffffff16565b507f7445c6598e1b553f076d507692eab3dceef0d608757141b53e9e56aa8bbaf48382858581518110613f2057613f206155fa565b6020026020010151602001518381518110613f3d57613f3d6155fa565b6020026020010151604051613f53929190615dde565b60405180910390a180613f658161598b565b915050613e73565b505080613f799061598b565b9050613e01565b5050565b5f6110ae8483856142f8565b5f6110ae848484613dd2565b613fc87f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc284848461477c565b613fdd6001600160a01b03861633308661478c565b613fe7818361480b565b60408051848152602081018490526001600160a01b0383169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a361403984848484614862565b5050505050565b825480156141bd5783806140556001846155e7565b81548110614065576140656155fa565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a90920490931602179055906140c690836155e7565b90505b8363ffffffff1681111561416d57846140e36001836155e7565b815481106140f3576140f36155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16858281548110614129576141296155fa565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808061416590615e01565b9150506140c9565b5081848463ffffffff1681548110614187576141876155fa565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550611477565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b606061388e8383604051806060016040528060278152602001615f0e6027913961486c565b61422e84848484614784565b336001600160a01b03821614614299576001600160a01b0381165f9081526004602090815260408083203384529091529020545f1981146142975761427384826155e7565b6001600160a01b0383165f9081526004602090815260408083203384529091529020555b505b6142a381846148d6565b60408051858152602081018590526001600160a01b03808416929085169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a46114778483614935565b82820281151584158583048514171661430f575f80fd5b0492915050565b815f0361433657604051632db38d0560e01b815260040160405180910390fd5b806001600160a01b03167f00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd6001600160a01b031663b93f9b0a846040518263ffffffff1660e01b815260040161438e91815260200190565b602060405180830381865afa1580156143a9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143cd9190615a65565b6001600160a01b031614613f8057604051634ee204d760e01b815260040160405180910390fd5b5f6143fd613275565b5f806144085f613895565b6001600160a01b0387165f90815260036020526040812054929450909250906144329084846139a9565b90505f61443f600161332c565b90508082111561444f5780614451565b815b9450851561446457611f70858585613f84565b5050505092915050565b5f60405163a9059cbb60e01b815283600482015282602482015260205f6044835f895af13d15601f3d1160015f5114161716915050806114775760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606401610eab565b6007545f906001600160a01b03168015801590614569575060405163b700961360e01b81526001600160a01b0382169063b70096139061452a90879030908890600401615768565b602060405180830381865afa158015614545573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906145699190615795565b806110ae57506006546001600160a01b03858116911614949350505050565b63ffffffff81165f908152600d6020526040812054600160a01b900460ff16156145b357505f919050565b63ffffffff82165f908152600d60205260409081902080549151637d2872e960e11b81526001600160a01b039092169163fa50e5d2916145fe91600182019160020190600401615e16565b602060405180830381865afa158015614619573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061111c9190615b2d565b815463ffffffff8216811161468a5760405162461bcd60e51b8152602060048201526013602482015272496e646578206f7574206f6620626f756e647360681b6044820152606401610eab565b63ffffffff82165b61469d6001836155e7565b81101561473a57836146b082600161560e565b815481106146c0576146c06155fa565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff168482815481106146f6576146f66155fa565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff16021790555080806147329061598b565b915050614692565b508280548061474b5761474b615e43565b5f8281526020902060085f1990920191820401805463ffffffff600460078516026101000a02191690559055505050565b6147846139c1565b611477613275565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f5114161716915050806140395760405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606401610eab565b8060025f82825461481c919061560e565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481525f80516020615f3583398151915291015b60405180910390a35050565b6114778484614c8a565b60605f80856001600160a01b0316856040516148889190615e57565b5f60405180830381855af49150503d805f81146148c0576040519150601f19603f3d011682016040523d82523d5f602084013e6148c5565b606091505b509150915061195986838387614d16565b6001600160a01b0382165f90815260036020526040812080548392906148fd9084906155e7565b90915550506002805482900390556040518181525f906001600160a01b038416905f80516020615f3583398151915290602001614856565b61495c60405180608001604052805f81526020015f81526020015f81526020015f81525090565b600954604051630226614760e01b81526001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28116600483015290911690630226614790602401602060405180830381865afa1580156149c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906149e89190615b2d565b6040820152614a187f0000000000000000000000000000000000000000000000000000000000000012600a615d41565b6060820152600a545f5b81811015614c67575f600a8281548110614a3e57614a3e6155fa565b5f9182526020822060088204015460079091166004026101000a900463ffffffff169150614a6b82614588565b9050805f03614a7b575050614c57565b5f614a8583613808565b600954604051630226614760e01b81526001600160a01b038084166004830152929350911690630226614790602401602060405180830381865afa158015614acf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614af39190615b2d565b865f018181525050806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015614b37573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614b5b9190615a4a565b614b6690600a615d41565b6020870181905286515f918291614b9091614b8987670de0b6b3a7640000615e72565b91906142f8565b9050614baf88606001518960400151836142f89092919063ffffffff16565b9150614bc3670de0b6b3a764000083615e89565b9150505f89821115614c26575f614bf189604001518a606001518d670de0b6b3a7640000614b899190615e72565b60208a01518a51919250614c07918391906142f8565b9150614c1b670de0b6b3a764000083615e89565b91505f9a5050614c35565b5082614c32828b6155e7565b99505b614c4085828b614d8e565b895f03614c51575050505050614c67565b50505050505b614c608161598b565b9050614a22565b5083156114775760405163cc5ea39b60e01b815260048101859052602401610eab565b63ffffffff82165f908152600d602052604090819020805491516001600160a01b0390921691611477916369445c3160e01b91614cd4918691600182019160020190602401615ea8565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526001600160a01b038316906141fd565b60608315614d845782515f03614d7d576001600160a01b0385163b614d7d5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610eab565b50816110ae565b6110ae8383614ddc565b63ffffffff83165f908152600d602052604090819020805491516001600160a01b03909216916140399163c9111bd760e01b91614cd491879187916001810191600290910190602401615ed2565b815115614dec5781518083602001fd5b8060405162461bcd60e51b8152600401610eab9190614ea5565b508054614e129061559b565b5f825580601f10614e21575050565b601f0160209004905f5260205f2090810190614e3d9190614e40565b50565b5b80821115614e54575f8155600101614e41565b5090565b5f5b83811015614e72578181015183820152602001614e5a565b50505f910152565b5f8151808452614e91816020860160208601614e58565b601f01601f19169290920160200192915050565b602081525f61388e6020830184614e7a565b803563ffffffff81168114614eca575f80fd5b919050565b5f60208284031215614edf575f80fd5b61388e82614eb7565b5f60208284031215614ef8575f80fd5b5035919050565b6001600160a01b0381168114614e3d575f80fd5b5f8060408385031215614f24575f80fd5b8235614f2f81614eff565b946020939093013593505050565b634e487b7160e01b5f52604160045260245ffd5b604080519081016001600160401b0381118282101715614f7357614f73614f3d565b60405290565b604051601f8201601f191681016001600160401b0381118282101715614fa157614fa1614f3d565b604052919050565b5f6001600160401b03821115614fc157614fc1614f3d565b50601f01601f191660200190565b5f82601f830112614fde575f80fd5b8135614ff1614fec82614fa9565b614f79565b818152846020838601011115615005575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f8060808587031215615034575f80fd5b843561503f81614eff565b9350602085013561504f81614eff565b92506040850135915060608501356001600160401b03811115615070575f80fd5b61507c87828801614fcf565b91505092959194509250565b5f60208284031215615098575f80fd5b813561388e81614eff565b5f805f606084860312156150b5575f80fd5b83356150c081614eff565b925060208401356150d081614eff565b929592945050506040919091013590565b5f805f606084860312156150f3575f80fd5b83356150fe81614eff565b925060208401359150604084013561511581614eff565b809150509250925092565b8015158114614e3d575f80fd5b5f806040838503121561513e575f80fd5b61514783614eb7565b9150602083013561515781615120565b809150509250929050565b5f805f60608486031215615174575f80fd5b61517d84614eb7565b925061518b60208501614eb7565b9150604084013561511581615120565b602080825282518282018190525f9190848201906040850190845b818110156151d857835163ffffffff16835292840192918401916001016151b6565b50909695505050505050565b5f8083601f8401126151f4575f80fd5b5081356001600160401b0381111561520a575f80fd5b6020830191508360208260051b8501011115615224575f80fd5b9250929050565b5f806020838503121561523c575f80fd5b82356001600160401b03811115615251575f80fd5b61525d858286016151e4565b90969095509350505050565b5f60208284031215615279575f80fd5b81356001600160c01b038116811461388e575f80fd5b5f80604083850312156152a0575f80fd5b82359150602083013561515781614eff565b5f805f606084860312156152c4575f80fd5b83356152cf81614eff565b92506152dd60208501614eb7565b91506152eb60408501614eb7565b90509250925092565b5f805f8060808587031215615307575f80fd5b61531085614eb7565b935061531e60208601614eb7565b925060408501356001600160401b03811115615338575f80fd5b61534487828801614fcf565b925050606085013561535581615120565b939692955090935050565b5f805f60608486031215615372575f80fd5b83359250602084013561538481614eff565b9150604084013561511581614eff565b5f602082840312156153a4575f80fd5b81356001600160401b038116811461388e575f80fd5b5f805f606084860312156153cc575f80fd5b83356153d781615120565b9250602084013561ffff81168114615384575f80fd5b60ff81168114614e3d575f80fd5b5f805f805f805f60e0888a031215615411575f80fd5b873561541c81614eff565b9650602088013561542c81614eff565b95506040880135945060608801359350608088013561544a816153ed565b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215615478575f80fd5b823561548381614eff565b9150602083013561515781614eff565b5f805f805f805f806080898b0312156154aa575f80fd5b88356001600160401b03808211156154c0575f80fd5b6154cc8c838d016151e4565b909a50985060208b01359150808211156154e4575f80fd5b6154f08c838d016151e4565b909850965060408b0135915080821115615508575f80fd5b6155148c838d016151e4565b909650945060608b013591508082111561552c575f80fd5b818b0191508b601f83011261553f575f80fd5b81358181111561554d575f80fd5b8c602082850101111561555e575f80fd5b6020830194508093505050509295985092959890939650565b6020808252600a90820152695245454e5452414e435960b01b604082015260600190565b600181811c908216806155af57607f821691505b6020821081036155cd57634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561111c5761111c6155d3565b634e487b7160e01b5f52603260045260245ffd5b8082018082111561111c5761111c6155d3565b5f6001600160401b0382111561563957615639614f3d565b5060051b60200190565b5f615650614fec84615621565b8381529050602080820190600585901b84018681111561566e575f80fd5b845b81811015615751576001600160401b03808235111561568d575f80fd5b813587016040818b0312156156a0575f80fd5b6156a8614f51565b6156b28235614eff565b8135815285820135838111156156c6575f80fd5b8083019250508a601f8301126156da575f80fd5b81356156e8614fec82615621565b81815260059190911b8301870190878101908d831115615706575f80fd5b8885015b8381101561573b57868135111561571f575f80fd5b61572e8f8b8335890101614fcf565b835291890191890161570a565b5083890152505086525050928201928201615670565b505050509392505050565b5f61388e368484615643565b6001600160a01b0393841681529190921660208201526001600160e01b0319909116604082015260600190565b5f602082840312156157a5575f80fd5b815161388e81615120565b5f805f606084860312156157c2575f80fd5b83516157cd81614eff565b60208501519093506157de81615120565b60408501519092506001600160401b038111156157f9575f80fd5b8401601f81018613615809575f80fd5b8051615817614fec82614fa9565b81815287602083850101111561582b575f80fd5b61583c826020830160208601614e58565b8093505050509250925092565b601f8211156127b6575f81815260208120601f850160051c8101602086101561586f5750805b601f850160051c820191505b81811015612b865782815560010161587b565b81516001600160401b038111156158a7576158a7614f3d565b6158bb816158b5845461559b565b84615849565b602080601f8311600181146158ee575f84156158d75750858301515b5f19600386901b1c1916600185901b178555612b86565b5f85815260208120601f198616915b8281101561591c578886015182559484019460019091019084016158fd565b508582101561593957878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f808335601e1984360301811261595e575f80fd5b8301803591506001600160401b03821115615977575f80fd5b602001915036819003821315615224575f80fd5b5f6001820161599c5761599c6155d3565b5060010190565b61ffff8281168282160390808211156159be576159be6155d3565b5092915050565b61ffff8181168382160190808211156159be576159be6155d3565b5f602082840312156159f0575f80fd5b81356001600160401b03811115615a05575f80fd5b8201601f81018413615a15575f80fd5b6110ae84823560208401615643565b6020808252600c908201526b15539055551213d49256915160a21b604082015260600190565b5f60208284031215615a5a575f80fd5b815161388e816153ed565b5f60208284031215615a75575f80fd5b815161388e81614eff565b5f8151808452602080850194508084015f5b83811015615ab75781516001600160a01b031687529582019590820190600101615a92565b509495945050505050565b5f8151808452602080850194508084015f5b83811015615ab757815187529582019590820190600101615ad4565b606081525f615b026060830186615a80565b8281036020840152615b148186615ac2565b91505060018060a01b0383166040830152949350505050565b5f60208284031215615b3d575f80fd5b5051919050565b60a081525f615b5660a0830188615a80565b8281036020840152615b688188615ac2565b90508281036040840152615b7c8187615a80565b90508281036060840152615b908186615ac2565b91505060018060a01b03831660808301529695505050505050565b5f8154615bb78161559b565b808552602060018381168015615bd45760018114615bee57615c19565b60ff1985168884015283151560051b880183019550615c19565b865f52825f205f5b85811015615c115781548a8201860152908301908401615bf6565b890184019650505b505050505092915050565b602081525f61388e6020830184615bab565b5f805f60608486031215615c48575f80fd5b8351925060208401519150604084015161511581615120565b600181815b80851115615c9b57815f1904821115615c8157615c816155d3565b80851615615c8e57918102915b93841c9390800290615c66565b509250929050565b5f82615cb15750600161111c565b81615cbd57505f61111c565b8160018114615cd35760028114615cdd57615cf9565b600191505061111c565b60ff841115615cee57615cee6155d3565b50506001821b61111c565b5060208310610133831016604e8410600b8410161715615d1c575081810a61111c565b615d268383615c61565b805f1904821115615d3957615d396155d3565b029392505050565b5f61388e60ff841683615ca3565b63ffffffff8281168282160390808211156159be576159be6155d3565b5f808354615d798161559b565b60018281168015615d915760018114615da657615dd2565b60ff1984168752821515830287019450615dd2565b875f526020805f205f5b85811015615dc95781548a820152908401908201615db0565b50505082870194505b50929695505050505050565b6001600160a01b03831681526040602082018190525f906110ae90830184614e7a565b5f81615e0f57615e0f6155d3565b505f190190565b604081525f615e286040830185615bab565b8281036020840152615e3a8185615bab565b95945050505050565b634e487b7160e01b5f52603160045260245ffd5b5f8251615e68818460208701614e58565b9190910192915050565b808202811582820484141761111c5761111c6155d3565b5f82615ea357634e487b7160e01b5f52601260045260245ffd5b500490565b838152606060208201525f615ec06060830185615bab565b82810360408401526119598185615bab565b8481526001600160a01b03841660208201526080604082018190525f90615efb90830185615bab565b8281036060840152611f708185615bab56fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa264697066735822122001ee3b7a5e5b203fe12552069e6757861290b0f372c1673e65521345b9de750b64736f6c63430008150033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000002322ba43eff1542b6a7baed35e66099ea0d12bd100000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000005af3107a400000000000000000000000000000000000000000000000000006f05b59d3b200000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8000000000000000000000000000000000000000000000000000000000000001045746865722e66692d4c69717569643100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b4c5149444554484649563100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000001
-----Decoded View---------------
Arg [0] : _owner (address): 0x2322ba43eFF1542b6A7bAeD35e66099Ea0d12Bd1
Arg [1] : _registry (address): 0x37912f4c0F0d916890eBD755BF6d1f0A0e059BbD
Arg [2] : _asset (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
Arg [3] : _name (string): Ether.fi-Liquid1
Arg [4] : _symbol (string): LQIDETHFIV1
Arg [5] : _holdingPosition (uint32): 1
Arg [6] : _holdingPositionConfig (bytes): 0x0000000000000000000000000000000000000000000000000000000000000001
Arg [7] : _initialDeposit (uint256): 100000000000000
Arg [8] : _strategistPlatformCut (uint64): 500000000000000000
Arg [9] : _shareSupplyCap (uint192): 6277101735386680763835789423207666416102355444464034512895
Arg [10] : _balancerVault (address): 0xBA12222222228d8Ba445958a75a0704d566BF2C8
-----Encoded View---------------
17 Constructor Arguments found :
Arg [0] : 0000000000000000000000002322ba43eff1542b6a7baed35e66099ea0d12bd1
Arg [1] : 00000000000000000000000037912f4c0f0d916890ebd755bf6d1f0a0e059bbd
Arg [2] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000160
Arg [4] : 00000000000000000000000000000000000000000000000000000000000001a0
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [6] : 00000000000000000000000000000000000000000000000000000000000001e0
Arg [7] : 00000000000000000000000000000000000000000000000000005af3107a4000
Arg [8] : 00000000000000000000000000000000000000000000000006f05b59d3b20000
Arg [9] : 0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff
Arg [10] : 000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000010
Arg [12] : 45746865722e66692d4c69717569643100000000000000000000000000000000
Arg [13] : 000000000000000000000000000000000000000000000000000000000000000b
Arg [14] : 4c51494445544846495631000000000000000000000000000000000000000000
Arg [15] : 0000000000000000000000000000000000000000000000000000000000000020
Arg [16] : 0000000000000000000000000000000000000000000000000000000000000001
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.