Overview
S Balance
0 S
S Value
$0.00More Info
Private Name Tags
ContractCreator
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Source Code Verified (Exact Match)
Contract Name:
IchiSwapXFarmStrategy
Compiler Version
v0.8.23+commit.f704f362
Optimization Enabled:
Yes with 200 runs
Other Settings:
shanghai EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {StrategyBase} from "./base/StrategyBase.sol"; import {LPStrategyBase} from "./base/LPStrategyBase.sol"; import {FarmingStrategyBase} from "./base/FarmingStrategyBase.sol"; import {StrategyLib} from "./libs/StrategyLib.sol"; import {StrategyIdLib} from "./libs/StrategyIdLib.sol"; import {FarmMechanicsLib} from "./libs/FarmMechanicsLib.sol"; import {ISFLib} from "./libs/ISFLib.sol"; import {IFactory} from "../interfaces/IFactory.sol"; import {IAmmAdapter} from "../interfaces/IAmmAdapter.sol"; import {ICAmmAdapter} from "../interfaces/ICAmmAdapter.sol"; import {IStrategy} from "../interfaces/IStrategy.sol"; import {IFarmingStrategy} from "../interfaces/IFarmingStrategy.sol"; import {ILPStrategy} from "../interfaces/ILPStrategy.sol"; import {IControllable} from "../interfaces/IControllable.sol"; import {IPlatform} from "../interfaces/IPlatform.sol"; import {VaultTypeLib} from "../core/libs/VaultTypeLib.sol"; import {CommonLib} from "../core/libs/CommonLib.sol"; import {AmmAdapterIdLib} from "../adapters/libs/AmmAdapterIdLib.sol"; import {IICHIVaultV4} from "../integrations/ichi/IICHIVaultV4.sol"; import {IGaugeV2_CL} from "../integrations/swapx/IGaugeV2_CL.sol"; import {IAlgebraPool} from "../integrations/algebrav4/IAlgebraPool.sol"; import {IVoterV3} from "../integrations/swapx/IVoterV3.sol"; /// @title Earn SwapX farm rewards by Ichi ALM /// @author Alien Deployer (https://github.com/a17) contract IchiSwapXFarmStrategy is LPStrategyBase, FarmingStrategyBase { using SafeERC20 for IERC20; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IControllable string public constant VERSION = "1.0.0"; uint internal constant PRECISION = 10 ** 18; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DATA TYPES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ struct PreviewDepositVars { uint32 twapPeriod; uint32 auxTwapPeriod; uint price; uint twap; uint auxTwap; uint pool0; uint pool1; address pool; address token0; address token1; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INITIALIZATION */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IStrategy function initialize(address[] memory addresses, uint[] memory nums, int24[] memory ticks) public initializer { if (addresses.length != 2 || nums.length != 1 || ticks.length != 0) { revert IControllable.IncorrectInitParams(); } IFactory.Farm memory farm = _getFarm(addresses[0], nums[0]); if (farm.addresses.length != 2 || farm.nums.length != 0 || farm.ticks.length != 0) { revert IFarmingStrategy.BadFarm(); } __LPStrategyBase_init( LPStrategyBaseInitParams({ id: StrategyIdLib.ICHI_SWAPX_FARM, platform: addresses[0], vault: addresses[1], pool: farm.pool, underlying: farm.addresses[0] }) ); __FarmingStrategyBase_init(addresses[0], nums[0]); address[] memory _assets = assets(); IERC20(_assets[0]).forceApprove(farm.addresses[0], type(uint).max); IERC20(_assets[1]).forceApprove(farm.addresses[0], type(uint).max); IERC20(farm.addresses[0]).forceApprove(farm.addresses[1], type(uint).max); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view override(LPStrategyBase, FarmingStrategyBase) returns (bool) { return super.supportsInterface(interfaceId); } /// @inheritdoc IFarmingStrategy function canFarm() external view override returns (bool) { IFactory.Farm memory farm = _getFarm(); return farm.status == 0; } /// @inheritdoc FarmingStrategyBase function stakingPool() external view override returns (address) { IFactory.Farm memory farm = _getFarm(); return farm.addresses[1]; } /// @inheritdoc ILPStrategy function ammAdapterId() public pure override returns (string memory) { return AmmAdapterIdLib.ALGEBRA_V4; } /// @inheritdoc IStrategy function getRevenue() external pure returns (address[] memory __assets, uint[] memory amounts) { __assets = new address[](0); amounts = new uint[](0); } /// @inheritdoc IStrategy function initVariants(address platform_) public view returns (string[] memory variants, address[] memory addresses, uint[] memory nums, int24[] memory ticks) { ICAmmAdapter _ammAdapter = ICAmmAdapter(IPlatform(platform_).ammAdapter(keccak256(bytes(ammAdapterId()))).proxy); addresses = new address[](0); ticks = new int24[](0); IFactory.Farm[] memory farms = IFactory(IPlatform(platform_).factory()).farms(); uint len = farms.length; //slither-disable-next-line uninitialized-local uint localTtotal; //nosemgrep for (uint i; i < len; ++i) { //nosemgrep IFactory.Farm memory farm = farms[i]; //nosemgrep if (farm.status == 0 && CommonLib.eq(farm.strategyLogicId, strategyLogicId())) { ++localTtotal; } } variants = new string[](localTtotal); nums = new uint[](localTtotal); localTtotal = 0; //nosemgrep for (uint i; i < len; ++i) { //nosemgrep IFactory.Farm memory farm = farms[i]; //nosemgrep if (farm.status == 0 && CommonLib.eq(farm.strategyLogicId, strategyLogicId())) { nums[localTtotal] = i; //slither-disable-next-line calls-loop variants[localTtotal] = _generateDescription(farm, _ammAdapter); ++localTtotal; } } } /// @inheritdoc IStrategy function isHardWorkOnDepositAllowed() external pure returns (bool allowed) { allowed = true; } /// @inheritdoc IStrategy function isReadyForHardWork() external view returns (bool) { return total() != 0; } /// @inheritdoc IFarmingStrategy function farmMechanics() external pure returns (string memory) { return FarmMechanicsLib.CLASSIC; } /// @inheritdoc IStrategy function supportedVaultTypes() external pure override(LPStrategyBase, StrategyBase) returns (string[] memory types) { types = new string[](1); types[0] = VaultTypeLib.COMPOUNDING; } /// @inheritdoc IStrategy function strategyLogicId() public pure override returns (string memory) { return StrategyIdLib.ICHI_SWAPX_FARM; } /// @inheritdoc IStrategy function getAssetsProportions() public view returns (uint[] memory proportions) { StrategyBaseStorage storage __$__ = _getStrategyBaseStorage(); IICHIVaultV4 _underlying = IICHIVaultV4(__$__._underlying); proportions = new uint[](2); if (_underlying.allowToken0()) { proportions[0] = 1e18; } else { proportions[1] = 1e18; } } /// @inheritdoc IStrategy function getSpecificName() external view override returns (string memory, bool) { IFactory.Farm memory farm = _getFarm(); IICHIVaultV4 _ivault = IICHIVaultV4(farm.addresses[0]); address allowedToken = _ivault.allowToken0() ? _ivault.token0() : _ivault.token1(); string memory symbol = IERC20Metadata(allowedToken).symbol(); return (symbol, false); } /// @inheritdoc IStrategy function description() external view returns (string memory) { IFarmingStrategy.FarmingStrategyBaseStorage storage $f = _getFarmingStrategyBaseStorage(); ILPStrategy.LPStrategyBaseStorage storage $lp = _getLPStrategyBaseStorage(); IFactory.Farm memory farm = IFactory(IPlatform(platform()).factory()).farm($f.farmId); return _generateDescription(farm, $lp.ammAdapter); } /// @inheritdoc IStrategy function extra() external pure returns (bytes32) { return CommonLib.bytesToBytes32(abi.encodePacked(bytes3(0x965fff), bytes3(0x000000))); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STRATEGY BASE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc StrategyBase function _assetsAmounts() internal view override returns (address[] memory assets_, uint[] memory amounts_) { StrategyBaseStorage storage __$__ = _getStrategyBaseStorage(); assets_ = __$__._assets; uint value = __$__.total; IICHIVaultV4 _underlying = IICHIVaultV4(__$__._underlying); (uint amount0, uint amount1) = _underlying.getTotalAmounts(); uint totalSupply = _underlying.totalSupply(); amounts_ = new uint[](2); amounts_[0] = amount0 * value / totalSupply; amounts_[1] = amount1 * value / totalSupply; } /// @inheritdoc StrategyBase function _previewDepositAssets(uint[] memory amountsMax) internal view override(StrategyBase, LPStrategyBase) returns (uint[] memory amountsConsumed, uint value) { StrategyBaseStorage storage __$__ = _getStrategyBaseStorage(); IICHIVaultV4 _underlying = IICHIVaultV4(__$__._underlying); amountsConsumed = new uint[](2); if (_underlying.allowToken0()) { amountsConsumed[0] = amountsMax[0]; } else { amountsConsumed[1] = amountsMax[1]; } PreviewDepositVars memory v; v.pool = _underlying.pool(); v.token0 = _underlying.token0(); v.token1 = _underlying.token1(); v.twapPeriod = _underlying.twapPeriod(); // Get spot price v.price = _fetchSpot(_underlying.token0(), _underlying.token1(), _underlying.currentTick(), PRECISION); // Get TWAP price v.twap = _fetchTwap(v.pool, v.token0, v.token1, v.twapPeriod, PRECISION); v.auxTwapPeriod = _underlying.auxTwapPeriod(); v.auxTwap = v.auxTwapPeriod > 0 ? _fetchTwap(v.pool, v.token0, v.token1, v.auxTwapPeriod, PRECISION) : v.twap; (uint pool0, uint pool1) = _underlying.getTotalAmounts(); // Calculate share value in token1 uint priceForDeposit = _getConservativePrice(v.price, v.twap, v.auxTwap, false, v.auxTwapPeriod); uint deposit0PricedInToken1 = amountsConsumed[0] * priceForDeposit / PRECISION; value = amountsConsumed[1] + deposit0PricedInToken1; uint totalSupply = _underlying.totalSupply(); if (totalSupply != 0) { uint priceForPool = _getConservativePrice(v.price, v.twap, v.auxTwap, true, v.auxTwapPeriod); uint pool0PricedInToken1 = pool0 * priceForPool / PRECISION; value = value * totalSupply / (pool0PricedInToken1 + pool1); } } /// @inheritdoc StrategyBase function _previewDepositUnderlying(uint amount) internal view override returns (uint[] memory amountsConsumed) { StrategyBaseStorage storage $ = _getStrategyBaseStorage(); IICHIVaultV4 alm = IICHIVaultV4($._underlying); (uint total0, uint total1) = alm.getTotalAmounts(); uint totalInAlm = alm.totalSupply(); amountsConsumed = new uint[](2); amountsConsumed[0] = total0 * amount / totalInAlm; amountsConsumed[1] = total1 * amount / totalInAlm; } /// @inheritdoc StrategyBase function _depositAssets(uint[] memory amounts, bool) internal override returns (uint value) { IFactory.Farm memory farm = _getFarm(); value = IICHIVaultV4(farm.addresses[0]).deposit(amounts[0], amounts[1], address(this)); IGaugeV2_CL(farm.addresses[1]).deposit(value); StrategyBaseStorage storage $base = _getStrategyBaseStorage(); $base.total += value; } /// @inheritdoc StrategyBase function _depositUnderlying(uint amount) internal override returns (uint[] memory amountsConsumed) { IFactory.Farm memory farm = _getFarm(); IGaugeV2_CL(farm.addresses[1]).deposit(amount); amountsConsumed = _previewDepositUnderlying(amount); StrategyBaseStorage storage $base = _getStrategyBaseStorage(); $base.total += amount; } /// @inheritdoc StrategyBase function _withdrawAssets(uint value, address receiver) internal override returns (uint[] memory amountsOut) { IFactory.Farm memory farm = _getFarm(); IGaugeV2_CL(farm.addresses[1]).withdraw(value); amountsOut = new uint[](2); (amountsOut[0], amountsOut[1]) = IICHIVaultV4(farm.addresses[0]).withdraw(value, receiver); StrategyBaseStorage storage $base = _getStrategyBaseStorage(); $base.total -= value; } /// @inheritdoc StrategyBase function _withdrawUnderlying(uint amount, address receiver) internal override { IFactory.Farm memory farm = _getFarm(); IGaugeV2_CL(farm.addresses[1]).withdraw(amount); IERC20(farm.addresses[0]).safeTransfer(receiver, amount); StrategyBaseStorage storage $base = _getStrategyBaseStorage(); $base.total -= amount; } /// @inheritdoc StrategyBase function _claimRevenue() internal override returns ( address[] memory __assets, uint[] memory __amounts, address[] memory __rewardAssets, uint[] memory __rewardAmounts ) { __assets = assets(); __amounts = new uint[](__assets.length); FarmingStrategyBaseStorage storage $f = _getFarmingStrategyBaseStorage(); __rewardAssets = $f._rewardAssets; uint balanceBefore = StrategyLib.balance(__rewardAssets[0]); __rewardAmounts = new uint[](1); IFactory.Farm memory farm = _getFarm(); IVoterV3 voter = IVoterV3(IGaugeV2_CL(farm.addresses[1]).DISTRIBUTION()); address[] memory gauges = new address[](1); gauges[0] = farm.addresses[1]; voter.claimRewards(gauges); __rewardAmounts[0] = StrategyLib.balance(__rewardAssets[0]) - balanceBefore; } /// @inheritdoc StrategyBase function _compound() internal override { uint[] memory proportions = getAssetsProportions(); uint[] memory amountsToDeposit = _swapForDepositProportion(proportions[0]); // nosemgrep if (amountsToDeposit[0] > 1 || amountsToDeposit[1] > 1) { uint valueToReceive; (amountsToDeposit, valueToReceive) = _previewDepositAssets(amountsToDeposit); if (valueToReceive > 10) { _depositAssets(amountsToDeposit, false); } } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL LOGIC */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /** * @notice returns equivalent _tokenOut for _amountIn, _tokenIn using spot price * @param _tokenIn token the input amount is in * @param _tokenOut token for the output amount * @param _tick tick for the spot price * @param _amountIn amount in _tokenIn * @return amountOut equivalent anount in _tokenOut */ function _fetchSpot( address _tokenIn, address _tokenOut, int24 _tick, uint _amountIn ) internal pure returns (uint amountOut) { return ISFLib.getQuoteAtTick(_tick, SafeCast.toUint128(_amountIn), _tokenIn, _tokenOut); } /** * @notice returns equivalent _tokenOut for _amountIn, _tokenIn using TWAP price * @param _pool Uniswap V3 pool address to be used for price checking * @param _tokenIn token the input amount is in * @param _tokenOut token for the output amount * @param _twapPeriod the averaging time period * @param _amountIn amount in _tokenIn * @return amountOut equivalent anount in _tokenOut */ function _fetchTwap( address _pool, address _tokenIn, address _tokenOut, uint32 _twapPeriod, uint _amountIn ) internal view returns (uint amountOut) { // Leave twapTick as a int256 to avoid solidity casting address basePlugin = _getBasePluginFromPool(_pool); int twapTick = ISFLib.consult(basePlugin, _twapPeriod); return ISFLib.getQuoteAtTick( int24(twapTick), // can assume safe being result from consult() SafeCast.toUint128(_amountIn), _tokenIn, _tokenOut ); } function _getBasePluginFromPool(address pool_) private view returns (address basePlugin) { basePlugin = IAlgebraPool(pool_).plugin(); // make sure the base plugin is connected to the pool require(ISFLib.isOracleConnectedToPool(basePlugin, pool_), "IV: diconnected plugin"); } /** * @notice Helper function to get the most conservative price * @param spot Current spot price * @param twap TWAP price * @param auxTwap Auxiliary TWAP price * @param isPool Flag indicating if the valuation is for the pool or deposit * @return price Most conservative price */ function _getConservativePrice( uint spot, uint twap, uint auxTwap, bool isPool, uint32 auxTwapPeriod ) internal pure returns (uint) { if (isPool) { // For pool valuation, use highest price to be conservative if (auxTwapPeriod > 0) { return Math.max(Math.max(spot, twap), auxTwap); } return Math.max(spot, twap); } else { // For deposit valuation, use lowest price to be conservative if (auxTwapPeriod > 0) { return Math.min(Math.min(spot, twap), auxTwap); } return Math.min(spot, twap); } } function _generateDescription( IFactory.Farm memory farm, IAmmAdapter _ammAdapter ) internal view returns (string memory) { //slither-disable-next-line calls-loop return string.concat( "Earn ", //slither-disable-next-line calls-loop CommonLib.implode(CommonLib.getSymbols(farm.rewardAssets), ", "), " and fees on SwapX pool ", //slither-disable-next-line calls-loop CommonLib.implode(CommonLib.getSymbols(_ammAdapter.poolTokens(farm.pool)), "-"), " by Ichi ", IERC20Metadata(farm.addresses[0]).symbol() ); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; import {IERC20Permit} from "../extensions/IERC20Permit.sol"; import {Address} from "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev An operation with an ERC20 token failed. */ error SafeERC20FailedOperation(address token); /** * @dev Indicates a failed `decreaseAllowance` request. */ error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value))); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); } /** * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no * value, non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { unchecked { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance < requestedDecrease) { revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); } forceApprove(token, spender, currentAllowance - requestedDecrease); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data); if (returndata.length != 0 && !abi.decode(returndata, (bool))) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.20; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeCast { /** * @dev Value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value); /** * @dev An int value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedIntToUint(int256 value); /** * @dev Value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedIntDowncast(uint8 bits, int256 value); /** * @dev An uint value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedUintToInt(uint256 value); /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits */ function toUint248(uint256 value) internal pure returns (uint248) { if (value > type(uint248).max) { revert SafeCastOverflowedUintDowncast(248, value); } return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits */ function toUint240(uint256 value) internal pure returns (uint240) { if (value > type(uint240).max) { revert SafeCastOverflowedUintDowncast(240, value); } return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits */ function toUint232(uint256 value) internal pure returns (uint232) { if (value > type(uint232).max) { revert SafeCastOverflowedUintDowncast(232, value); } return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { if (value > type(uint224).max) { revert SafeCastOverflowedUintDowncast(224, value); } return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits */ function toUint216(uint256 value) internal pure returns (uint216) { if (value > type(uint216).max) { revert SafeCastOverflowedUintDowncast(216, value); } return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits */ function toUint208(uint256 value) internal pure returns (uint208) { if (value > type(uint208).max) { revert SafeCastOverflowedUintDowncast(208, value); } return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits */ function toUint200(uint256 value) internal pure returns (uint200) { if (value > type(uint200).max) { revert SafeCastOverflowedUintDowncast(200, value); } return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { if (value > type(uint192).max) { revert SafeCastOverflowedUintDowncast(192, value); } return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits */ function toUint184(uint256 value) internal pure returns (uint184) { if (value > type(uint184).max) { revert SafeCastOverflowedUintDowncast(184, value); } return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits */ function toUint176(uint256 value) internal pure returns (uint176) { if (value > type(uint176).max) { revert SafeCastOverflowedUintDowncast(176, value); } return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits */ function toUint168(uint256 value) internal pure returns (uint168) { if (value > type(uint168).max) { revert SafeCastOverflowedUintDowncast(168, value); } return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits */ function toUint160(uint256 value) internal pure returns (uint160) { if (value > type(uint160).max) { revert SafeCastOverflowedUintDowncast(160, value); } return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits */ function toUint152(uint256 value) internal pure returns (uint152) { if (value > type(uint152).max) { revert SafeCastOverflowedUintDowncast(152, value); } return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits */ function toUint144(uint256 value) internal pure returns (uint144) { if (value > type(uint144).max) { revert SafeCastOverflowedUintDowncast(144, value); } return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits */ function toUint136(uint256 value) internal pure returns (uint136) { if (value > type(uint136).max) { revert SafeCastOverflowedUintDowncast(136, value); } return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { if (value > type(uint128).max) { revert SafeCastOverflowedUintDowncast(128, value); } return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits */ function toUint120(uint256 value) internal pure returns (uint120) { if (value > type(uint120).max) { revert SafeCastOverflowedUintDowncast(120, value); } return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits */ function toUint112(uint256 value) internal pure returns (uint112) { if (value > type(uint112).max) { revert SafeCastOverflowedUintDowncast(112, value); } return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits */ function toUint104(uint256 value) internal pure returns (uint104) { if (value > type(uint104).max) { revert SafeCastOverflowedUintDowncast(104, value); } return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { if (value > type(uint96).max) { revert SafeCastOverflowedUintDowncast(96, value); } return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits */ function toUint88(uint256 value) internal pure returns (uint88) { if (value > type(uint88).max) { revert SafeCastOverflowedUintDowncast(88, value); } return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits */ function toUint80(uint256 value) internal pure returns (uint80) { if (value > type(uint80).max) { revert SafeCastOverflowedUintDowncast(80, value); } return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits */ function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { if (value > type(uint64).max) { revert SafeCastOverflowedUintDowncast(64, value); } return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits */ function toUint56(uint256 value) internal pure returns (uint56) { if (value > type(uint56).max) { revert SafeCastOverflowedUintDowncast(56, value); } return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits */ function toUint48(uint256 value) internal pure returns (uint48) { if (value > type(uint48).max) { revert SafeCastOverflowedUintDowncast(48, value); } return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { if (value > type(uint40).max) { revert SafeCastOverflowedUintDowncast(40, value); } return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { if (value > type(uint32).max) { revert SafeCastOverflowedUintDowncast(32, value); } return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits */ function toUint24(uint256 value) internal pure returns (uint24) { if (value > type(uint24).max) { revert SafeCastOverflowedUintDowncast(24, value); } return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { if (value > type(uint16).max) { revert SafeCastOverflowedUintDowncast(16, value); } return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits */ function toUint8(uint256 value) internal pure returns (uint8) { if (value > type(uint8).max) { revert SafeCastOverflowedUintDowncast(8, value); } return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { if (value < 0) { revert SafeCastOverflowedIntToUint(value); } return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(248, value); } } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(240, value); } } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(232, value); } } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(224, value); } } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(216, value); } } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(208, value); } } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(200, value); } } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(192, value); } } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(184, value); } } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(176, value); } } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(168, value); } } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(160, value); } } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(144, value); } } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(136, value); } } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(128, value); } } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(112, value); } } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(104, value); } } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(96, value); } } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(88, value); } } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(80, value); } } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(72, value); } } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(64, value); } } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(56, value); } } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(48, value); } } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(40, value); } } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(32, value); } } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(24, value); } } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(16, value); } } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(8, value); } } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive if (value > uint256(type(int256).max)) { revert SafeCastOverflowedUintToInt(value); } return int256(value); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol) pragma solidity ^0.8.20; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Muldiv operation overflow. */ error MathOverflowedMulDiv(); enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an overflow flag. */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. return a / b; } // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by * Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (denominator <= prod1) { revert MathOverflowedMulDiv(); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. uint256 twos = denominator & (0 - denominator); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also // works in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "../../core/base/Controllable.sol"; import "../../core/libs/VaultTypeLib.sol"; import "../libs/StrategyLib.sol"; import "../../interfaces/IStrategy.sol"; import "../../interfaces/IVault.sol"; /// @dev Base universal strategy /// Changelog: /// 2.0.0: previewDepositAssetsWrite; use platform.getCustomVaultFee /// 1.1.0: autoCompoundingByUnderlyingProtocol(), virtual total() /// @author Alien Deployer (https://github.com/a17) /// @author JodsMigel (https://github.com/JodsMigel) abstract contract StrategyBase is Controllable, IStrategy { using SafeERC20 for IERC20; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Version of StrategyBase implementation string public constant VERSION_STRATEGY_BASE = "2.0.0"; // keccak256(abi.encode(uint256(keccak256("erc7201:stability.StrategyBase")) - 1)) & ~bytes32(uint256(0xff)); bytes32 private constant STRATEGYBASE_STORAGE_LOCATION = 0xb14b643f49bed6a2c6693bbd50f68dc950245db265c66acadbfa51ccc8c3ba00; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INITIALIZATION */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ //slither-disable-next-line naming-convention function __StrategyBase_init( address platform_, string memory id_, address vault_, address[] memory assets_, address underlying_, uint exchangeAssetIndex_ ) internal onlyInitializing { __Controllable_init(platform_); StrategyBaseStorage storage $ = _getStrategyBaseStorage(); ($._id, $.vault, $._assets, $._underlying, $._exchangeAssetIndex) = (id_, vault_, assets_, underlying_, exchangeAssetIndex_); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* RESTRICTED ACTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ modifier onlyVault() { _requireVault(); _; } /// @inheritdoc IStrategy function depositAssets(uint[] memory amounts) external override onlyVault returns (uint value) { StrategyBaseStorage storage $ = _getStrategyBaseStorage(); if ($.lastHardWork == 0) { $.lastHardWork = block.timestamp; } _beforeDeposit(); return _depositAssets(amounts, true); } /// @inheritdoc IStrategy function withdrawAssets( address[] memory assets_, uint value, address receiver ) external virtual onlyVault returns (uint[] memory amountsOut) { _beforeWithdraw(); return _withdrawAssets(assets_, value, receiver); } function depositUnderlying(uint amount) external virtual override onlyVault returns (uint[] memory amountsConsumed) { _beforeDeposit(); return _depositUnderlying(amount); } function withdrawUnderlying(uint amount, address receiver) external virtual override onlyVault { _beforeWithdraw(); _withdrawUnderlying(amount, receiver); } /// @inheritdoc IStrategy function transferAssets( uint amount, uint total_, address receiver ) external onlyVault returns (uint[] memory amountsOut) { _beforeTransferAssets(); //slither-disable-next-line unused-return return StrategyLib.transferAssets(_getStrategyBaseStorage(), amount, total_, receiver); } /// @inheritdoc IStrategy function doHardWork() external onlyVault { _beforeDoHardWork(); StrategyBaseStorage storage $ = _getStrategyBaseStorage(); address _vault = $.vault; //slither-disable-next-line unused-return (uint tvl,) = IVault(_vault).tvl(); if (tvl > 0) { address _platform = platform(); uint exchangeAssetIndex = $._exchangeAssetIndex; ( address[] memory __assets, uint[] memory __amounts, address[] memory __rewardAssets, uint[] memory __rewardAmounts ) = _claimRevenue(); //slither-disable-next-line uninitialized-local uint totalBefore; if (!autoCompoundingByUnderlyingProtocol()) { __amounts[exchangeAssetIndex] += _liquidateRewards(__assets[exchangeAssetIndex], __rewardAssets, __rewardAmounts); uint[] memory amountsRemaining = StrategyLib.extractFees(_platform, _vault, $._id, __assets, __amounts); bool needCompound = _processRevenue(__assets, amountsRemaining); totalBefore = $.total; if (needCompound) { _compound(); } } else { // maybe this is not final logic // vault shares as fees can be used not only for autoCompoundingByUnderlyingProtocol strategies, // but for many strategies linked to CVault if this feature will be implemented IVault(_vault).hardWorkMintFeeCallback(__assets, __amounts); // call empty method only for coverage or them can be overriden _liquidateRewards(__assets[0], __rewardAssets, __rewardAmounts); _processRevenue(__assets, __amounts); _compound(); } StrategyLib.emitApr($, _platform, __assets, __amounts, tvl, totalBefore); } } /// @inheritdoc IStrategy function emergencyStopInvesting() external onlyGovernanceOrMultisig { // slither-disable-next-line unused-return _withdrawAssets(total(), address(this)); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(Controllable, IERC165) returns (bool) { return interfaceId == type(IStrategy).interfaceId || super.supportsInterface(interfaceId); } function strategyLogicId() public view virtual returns (string memory); /// @inheritdoc IStrategy function assets() public view virtual returns (address[] memory) { return _getStrategyBaseStorage()._assets; } /// @inheritdoc IStrategy function underlying() public view override returns (address) { return _getStrategyBaseStorage()._underlying; } /// @inheritdoc IStrategy function vault() public view override returns (address) { return _getStrategyBaseStorage().vault; } /// @inheritdoc IStrategy function total() public view virtual override returns (uint) { return _getStrategyBaseStorage().total; } /// @inheritdoc IStrategy function lastHardWork() public view override returns (uint) { return _getStrategyBaseStorage().lastHardWork; } /// @inheritdoc IStrategy function lastApr() public view override returns (uint) { return _getStrategyBaseStorage().lastApr; } /// @inheritdoc IStrategy function lastAprCompound() public view override returns (uint) { return _getStrategyBaseStorage().lastAprCompound; } /// @inheritdoc IStrategy function assetsAmounts() public view virtual returns (address[] memory assets_, uint[] memory amounts_) { (assets_, amounts_) = _assetsAmounts(); //slither-disable-next-line unused-return return StrategyLib.assetsAmountsWithBalances(assets_, amounts_); } /// @inheritdoc IStrategy function previewDepositAssets( address[] memory assets_, uint[] memory amountsMax ) public view virtual returns (uint[] memory amountsConsumed, uint value) { // nosemgrep if (assets_.length == 1 && assets_[0] == _getStrategyBaseStorage()._underlying && assets_[0] != address(0)) { if (amountsMax.length != 1) { revert IControllable.IncorrectArrayLength(); } value = amountsMax[0]; amountsConsumed = _previewDepositUnderlying(amountsMax[0]); } else { return _previewDepositAssets(assets_, amountsMax); } } /// @inheritdoc IStrategy function previewDepositAssetsWrite( address[] memory assets_, uint[] memory amountsMax ) external virtual returns (uint[] memory amountsConsumed, uint value) { // nosemgrep if (assets_.length == 1 && assets_[0] == _getStrategyBaseStorage()._underlying && assets_[0] != address(0)) { if (amountsMax.length != 1) { revert IControllable.IncorrectArrayLength(); } value = amountsMax[0]; amountsConsumed = _previewDepositUnderlyingWrite(amountsMax[0]); } else { return _previewDepositAssetsWrite(assets_, amountsMax); } } /// @inheritdoc IStrategy function autoCompoundingByUnderlyingProtocol() public view virtual returns (bool) { return false; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* Default implementations */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Invest underlying asset. Asset must be already on strategy contract balance. /// @return Cosumed amounts of invested assets function _depositUnderlying(uint /*amount*/ ) internal virtual returns (uint[] memory /*amountsConsumed*/ ) { revert(_getStrategyBaseStorage()._underlying == address(0) ? "no underlying" : "not implemented"); } /// @dev Wothdraw underlying invested and send to receiver function _withdrawUnderlying(uint, /*amount*/ address /*receiver*/ ) internal virtual { revert(_getStrategyBaseStorage()._underlying == address(0) ? "no underlying" : "not implemented"); } /// @dev Calculation of consumed amounts and liquidity/underlying value for provided amount of underlying function _previewDepositUnderlying(uint /*amount*/ ) internal view virtual returns (uint[] memory /*amountsConsumed*/ ) {} function _previewDepositUnderlyingWrite(uint amount) internal view virtual returns (uint[] memory amountsConsumed) { return _previewDepositUnderlying(amount); } /// @dev Can be overrided by derived base strategies for custom logic function _beforeDeposit() internal virtual {} /// @dev Can be overrided by derived base strategies for custom logic function _beforeWithdraw() internal virtual {} /// @dev Can be overrided by derived base strategies for custom logic function _beforeTransferAssets() internal virtual {} /// @dev Can be overrided by derived base strategies for custom logic function _beforeDoHardWork() internal virtual { if (!IStrategy(this).isReadyForHardWork()) { revert NotReadyForHardWork(); } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* Must be implemented by derived contracts */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IStrategy function supportedVaultTypes() external view virtual returns (string[] memory types); /// @dev Investing assets. Amounts must be on strategy contract balance. /// @param amounts Amounts of strategy assets to invest /// @param claimRevenue Claim revenue before investing /// @return value Output of liquidity value or underlying token amount function _depositAssets(uint[] memory amounts, bool claimRevenue) internal virtual returns (uint value); /// @dev Withdraw assets from investing and send to user. /// Here we give the user a choice of assets to withdraw if strategy support it. /// This full form of _withdrawAssets can be implemented only in inherited base strategy contract. /// @param assets_ Assets for withdrawal. Can contain not all strategy assets if it need. /// @param value Part of strategy total value to withdraw /// @param receiver User address /// @return amountsOut Amounts of assets sent to user function _withdrawAssets( address[] memory assets_, uint value, address receiver ) internal virtual returns (uint[] memory amountsOut); /// @dev Withdraw strategy assets from investing and send to user. /// This light form of _withdrawAssets is suitable for implementation into final strategy contract. /// @param value Part of strategy total value to withdraw /// @param receiver User address /// @return amountsOut Amounts of assets sent to user function _withdrawAssets(uint value, address receiver) internal virtual returns (uint[] memory amountsOut); /// @dev Claim all possible revenue to strategy contract balance and calculate claimed revenue after previous HardWork /// @return __assets Strategy assets /// @return __amounts Amounts of claimed revenue in form of strategy assets /// @return __rewardAssets Farming reward assets /// @return __rewardAmounts Amounts of claimed farming rewards function _claimRevenue() internal virtual returns ( address[] memory __assets, uint[] memory __amounts, address[] memory __rewardAssets, uint[] memory __rewardAmounts ); function _processRevenue( address[] memory assets_, uint[] memory amountsRemaining ) internal virtual returns (bool needCompound); function _liquidateRewards( address exchangeAsset, address[] memory rewardAssets_, uint[] memory rewardAmounts_ ) internal virtual returns (uint earnedExchangeAsset); /// @dev Reinvest strategy assets of strategy contract balance function _compound() internal virtual; /// @dev Strategy assets and amounts that strategy invests. Without assets on strategy contract balance /// @return assets_ Strategy assets /// @return amounts_ Amounts invested function _assetsAmounts() internal view virtual returns (address[] memory assets_, uint[] memory amounts_); /// @dev Calculation of consumed amounts and liquidity/underlying value for provided strategy assets and amounts. /// @dev This full form of _previewDepositAssets can be implemented only in inherited base strategy contract /// @param assets_ Strategy assets or part of them, if necessary /// @param amountsMax Amounts of specified assets available for investing /// @return amountsConsumed Consumed amounts of assets when investing /// @return value Liquidity value or underlying token amount minted when investing function _previewDepositAssets( address[] memory assets_, uint[] memory amountsMax ) internal view virtual returns (uint[] memory amountsConsumed, uint value); /// @dev Write version of _previewDepositAssets /// @param assets_ Strategy assets or part of them, if necessary /// @param amountsMax Amounts of specified assets available for investing /// @return amountsConsumed Consumed amounts of assets when investing /// @return value Liquidity value or underlying token amount minted when investing function _previewDepositAssetsWrite( address[] memory assets_, uint[] memory amountsMax ) internal virtual returns (uint[] memory amountsConsumed, uint value) { return _previewDepositAssets(assets_, amountsMax); } /// @dev Calculation of consumed amounts and liquidity/underlying value for provided strategy assets and amounts. /// Light form of _previewDepositAssets is suitable for implementation into final strategy contract. /// @param amountsMax Amounts of specified assets available for investing /// @return amountsConsumed Consumed amounts of assets when investing /// @return value Liquidity value or underlying token amount minted when investing function _previewDepositAssets(uint[] memory amountsMax) internal view virtual returns (uint[] memory amountsConsumed, uint value); /// @dev Write version of _previewDepositAssets /// @param amountsMax Amounts of specified assets available for investing /// @return amountsConsumed Consumed amounts of assets when investing /// @return value Liquidity value or underlying token amount minted when investing function _previewDepositAssetsWrite(uint[] memory amountsMax) internal virtual returns (uint[] memory amountsConsumed, uint value) { return _previewDepositAssets(amountsMax); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL LOGIC */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function _getStrategyBaseStorage() internal pure returns (StrategyBaseStorage storage $) { //slither-disable-next-line assembly assembly { $.slot := STRATEGYBASE_STORAGE_LOCATION } } function _requireVault() internal view { if (msg.sender != _getStrategyBaseStorage().vault) { revert IControllable.NotVault(); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "./StrategyBase.sol"; import "../libs/LPStrategyLib.sol"; import "../../interfaces/ILPStrategy.sol"; /// @dev Base liquidity providing strategy /// Changelog: /// 1.0.4: _swapForDepositProportion support all amm adapters /// @author Alien Deployer (https://github.com/a17) /// @author JodsMigel (https://github.com/JodsMigel) abstract contract LPStrategyBase is StrategyBase, ILPStrategy { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Version of LPStrategyBase implementation string public constant VERSION_LP_STRATEGY_BASE = "1.0.4"; // keccak256(abi.encode(uint256(keccak256("erc7201:stability.LPStrategyBase")) - 1)) & ~bytes32(uint256(0xff)); bytes32 private constant LPSTRATEGYBASE_STORAGE_LOCATION = 0xa6fdc931ca23c69f54119a0a2d6478619b5aa365084590a1fbc287668fbabe00; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INITIALIZATION */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ //slither-disable-next-line naming-convention function __LPStrategyBase_init(LPStrategyBaseInitParams memory params) internal onlyInitializing { LPStrategyBaseStorage storage $ = _getLPStrategyBaseStorage(); address[] memory _assets; uint exchangeAssetIndex; (_assets, exchangeAssetIndex) = LPStrategyLib.LPStrategyBase_init($, params.platform, params, ammAdapterId()); //slither-disable-next-line reentrancy-events __StrategyBase_init(params.platform, params.id, params.vault, _assets, params.underlying, exchangeAssetIndex); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(ILPStrategy).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc IStrategy function supportedVaultTypes() external view virtual override returns (string[] memory types) { types = new string[](3); types[0] = VaultTypeLib.COMPOUNDING; types[1] = VaultTypeLib.REWARDING; types[2] = VaultTypeLib.REWARDING_MANAGED; } /// @inheritdoc ILPStrategy function ammAdapterId() public view virtual returns (string memory); /// @inheritdoc ILPStrategy function pool() public view override returns (address) { return _getLPStrategyBaseStorage().pool; } /// @inheritdoc ILPStrategy function ammAdapter() public view returns (IAmmAdapter) { return _getLPStrategyBaseStorage().ammAdapter; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL LOGIC */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ //slither-disable-next-line dead-code function _previewDepositAssets(uint[] memory amountsMax) internal view virtual override returns (uint[] memory amountsConsumed, uint value) { LPStrategyBaseStorage storage $ = _getLPStrategyBaseStorage(); (value, amountsConsumed) = $.ammAdapter.getLiquidityForAmounts($.pool, amountsMax); } function _previewDepositAssets( address[] memory assets_, uint[] memory amountsMax ) internal view override returns (uint[] memory amountsConsumed, uint value) { LPStrategyLib.checkPreviewDepositAssets(assets_, assets(), amountsMax); return _previewDepositAssets(amountsMax); } function _withdrawAssets( address[] memory assets_, uint value, address receiver ) internal virtual override returns (uint[] memory amountsOut) { LPStrategyLib.checkAssets(assets_, assets()); return _withdrawAssets(value, receiver); } function _processRevenue( address[] memory assets_, uint[] memory amountsRemaining ) internal override returns (bool needCompound) { LPStrategyBaseStorage storage $ = _getLPStrategyBaseStorage(); return LPStrategyLib.processRevenue( platform(), vault(), $.ammAdapter, _getStrategyBaseStorage()._exchangeAssetIndex, $.pool, assets_, amountsRemaining ); } function _swapForDepositProportion(uint prop0Pool) internal returns (uint[] memory amountsToDeposit) { LPStrategyBaseStorage storage $ = _getLPStrategyBaseStorage(); return LPStrategyLib.swapForDepositProportion(platform(), $.ammAdapter, $.pool, assets(), prop0Pool); } function _getLPStrategyBaseStorage() internal pure returns (LPStrategyBaseStorage storage $) { //slither-disable-next-line assembly assembly { $.slot := LPSTRATEGYBASE_STORAGE_LOCATION } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "./StrategyBase.sol"; import "../libs/StrategyLib.sol"; import "../../interfaces/IStrategy.sol"; import "../../interfaces/IFactory.sol"; import "../../interfaces/IFarmingStrategy.sol"; import "../../interfaces/ISwapper.sol"; /// @title Base farming strategy /// @author Alien Deployer (https://github.com/a17) /// @author JodsMigel (https://github.com/JodsMigel) abstract contract FarmingStrategyBase is StrategyBase, IFarmingStrategy { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Version of FarmingStrategyBase implementation string public constant VERSION_FARMING_STRATEGY_BASE = "1.2.0"; // keccak256(abi.encode(uint256(keccak256("erc7201:stability.FarmingStrategyBase")) - 1)) & ~bytes32(uint256(0xff)); bytes32 private constant FARMINGSTRATEGYBASE_STORAGE_LOCATION = 0xe61f0a7b2953b9e28e48cc07562ad7979478dcaee972e68dcf3b10da2cba6000; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INITIALIZATION */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ //slither-disable-next-line naming-convention function __FarmingStrategyBase_init(address platform_, uint farmId_) internal onlyInitializing { StrategyLib.FarmingStrategyBase_init( _getFarmingStrategyBaseStorage(), _getStrategyBaseStorage()._id, platform_, farmId_ ); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* RESTRICTED ACTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IFarmingStrategy function refreshFarmingAssets() external onlyOperator { StrategyLib.updateFarmingAssets(_getFarmingStrategyBaseStorage(), platform()); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(StrategyBase) returns (bool) { return interfaceId == type(IFarmingStrategy).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc IFarmingStrategy function farmId() public view returns (uint) { return _getFarmingStrategyBaseStorage().farmId; } /// @inheritdoc IFarmingStrategy function farmingAssets() external view returns (address[] memory) { return _getFarmingStrategyBaseStorage()._rewardAssets; } /// @inheritdoc IFarmingStrategy function stakingPool() external view virtual returns (address) { return address(0); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* Providing farm data to derived contracts */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function _getFarm() internal view returns (IFactory.Farm memory) { return _getFarm(platform(), farmId()); } function _getFarm(address platform_, uint farmId_) internal view returns (IFactory.Farm memory) { return IFactory(IPlatform(platform_).factory()).farm(farmId_); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STRATEGY BASE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @inheritdoc StrategyBase function _liquidateRewards( address exchangeAsset, address[] memory rewardAssets_, uint[] memory rewardAmounts_ ) internal override returns (uint earnedExchangeAsset) { return StrategyLib.liquidateRewards(platform(), exchangeAsset, rewardAssets_, rewardAmounts_); } function _getFarmingStrategyBaseStorage() internal pure returns (FarmingStrategyBaseStorage storage $) { //slither-disable-next-line assembly assembly { $.slot := FARMINGSTRATEGYBASE_STORAGE_LOCATION } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "../../core/libs/ConstantsLib.sol"; import "../../core/libs/VaultTypeLib.sol"; import "../../core/libs/CommonLib.sol"; import "../../interfaces/IPlatform.sol"; import "../../interfaces/IVault.sol"; import "../../interfaces/IVaultManager.sol"; import "../../interfaces/IStrategyLogic.sol"; import "../../interfaces/IFactory.sol"; import "../../interfaces/IPriceReader.sol"; import "../../interfaces/ISwapper.sol"; import "../../interfaces/ILPStrategy.sol"; import "../../interfaces/IFarmingStrategy.sol"; library StrategyLib { using SafeERC20 for IERC20; /// @dev Reward pools may have low liquidity and 1% fees uint internal constant SWAP_REWARDS_PRICE_IMPACT_TOLERANCE = 7_000; struct ExtractFeesVars { IPlatform platform; uint feePlatform; uint amountPlatform; uint feeShareVaultManager; uint amountVaultManager; uint feeShareStrategyLogic; uint amountStrategyLogic; uint feeShareEcosystem; uint amountEcosystem; } function FarmingStrategyBase_init( IFarmingStrategy.FarmingStrategyBaseStorage storage $, string memory id, address platform, uint farmId ) external { $.farmId = farmId; IFactory.Farm memory farm = IFactory(IPlatform(platform).factory()).farm(farmId); if (keccak256(bytes(farm.strategyLogicId)) != keccak256(bytes(id))) { revert IFarmingStrategy.IncorrectStrategyId(); } updateFarmingAssets($, platform); $._rewardsOnBalance = new uint[](farm.rewardAssets.length); } function updateFarmingAssets(IFarmingStrategy.FarmingStrategyBaseStorage storage $, address platform) public { IFactory.Farm memory farm = IFactory(IPlatform(platform).factory()).farm($.farmId); address swapper = IPlatform(platform).swapper(); $._rewardAssets = farm.rewardAssets; uint len = farm.rewardAssets.length; // nosemgrep for (uint i; i < len; ++i) { IERC20(farm.rewardAssets[i]).forceApprove(swapper, type(uint).max); } } function transferAssets( IStrategy.StrategyBaseStorage storage $, uint amount, uint total_, address receiver ) external returns (uint[] memory amountsOut) { address[] memory assets = $._assets; uint len = assets.length; amountsOut = new uint[](len); // nosemgrep for (uint i; i < len; ++i) { amountsOut[i] = balance(assets[i]) * amount / total_; IERC20(assets[i]).transfer(receiver, amountsOut[i]); } } function extractFees( address platform, address vault, string memory _id, address[] memory assets_, uint[] memory amounts_ ) external returns (uint[] memory amountsRemaining) { ExtractFeesVars memory vars = ExtractFeesVars({ platform: IPlatform(platform), feePlatform: 0, amountPlatform: 0, feeShareVaultManager: 0, amountVaultManager: 0, feeShareStrategyLogic: 0, amountStrategyLogic: 0, feeShareEcosystem: 0, amountEcosystem: 0 }); (vars.feePlatform, vars.feeShareVaultManager, vars.feeShareStrategyLogic, vars.feeShareEcosystem) = vars.platform.getFees(); try vars.platform.getCustomVaultFee(vault) returns (uint vaultCustomFee) { if (vaultCustomFee != 0) { vars.feePlatform = vaultCustomFee; } } catch {} address vaultManagerReceiver = IVaultManager(vars.platform.vaultManager()).getRevenueReceiver(IVault(vault).tokenId()); //slither-disable-next-line unused-return uint strategyLogicTokenId = IFactory(vars.platform.factory()).strategyLogicConfig(keccak256(bytes(_id))).tokenId; address strategyLogicReceiver = IStrategyLogic(vars.platform.strategyLogic()).getRevenueReceiver(strategyLogicTokenId); uint len = assets_.length; amountsRemaining = new uint[](len); // nosemgrep for (uint i; i < len; ++i) { amounts_[i] = Math.min(amounts_[i], balance(assets_[i])); if (amounts_[i] > 0) { // revenue fee amount of assets_[i] vars.amountPlatform = amounts_[i] * vars.feePlatform / ConstantsLib.DENOMINATOR; amountsRemaining[i] = amounts_[i] - vars.amountPlatform; // VaultManager amount vars.amountVaultManager = vars.amountPlatform * vars.feeShareVaultManager / ConstantsLib.DENOMINATOR; // StrategyLogic amount vars.amountStrategyLogic = vars.amountPlatform * vars.feeShareStrategyLogic / ConstantsLib.DENOMINATOR; // Ecosystem amount vars.amountEcosystem = vars.amountPlatform * vars.feeShareEcosystem / ConstantsLib.DENOMINATOR; // Multisig share and amount uint multisigShare = ConstantsLib.DENOMINATOR - vars.feeShareVaultManager - vars.feeShareStrategyLogic - vars.feeShareEcosystem; uint multisigAmount = multisigShare > 0 ? vars.amountPlatform - vars.amountVaultManager - vars.amountStrategyLogic - vars.amountEcosystem : 0; // send amounts IERC20(assets_[i]).safeTransfer(vaultManagerReceiver, vars.amountVaultManager); IERC20(assets_[i]).safeTransfer(strategyLogicReceiver, vars.amountStrategyLogic); if (vars.amountEcosystem > 0) { IERC20(assets_[i]).safeTransfer(vars.platform.ecosystemRevenueReceiver(), vars.amountEcosystem); } if (multisigAmount > 0) { IERC20(assets_[i]).safeTransfer(vars.platform.multisig(), multisigAmount); } emit IStrategy.ExtractFees( vars.amountVaultManager, vars.amountStrategyLogic, vars.amountEcosystem, multisigAmount ); } } } function liquidateRewards( address platform, address exchangeAsset, address[] memory rewardAssets_, uint[] memory rewardAmounts_ ) external returns (uint earnedExchangeAsset) { ISwapper swapper = ISwapper(IPlatform(platform).swapper()); uint len = rewardAssets_.length; uint exchangeAssetBalanceBefore = balance(exchangeAsset); // nosemgrep for (uint i; i < len; ++i) { if (rewardAmounts_[i] > swapper.threshold(rewardAssets_[i])) { if (rewardAssets_[i] != exchangeAsset) { swapper.swap( rewardAssets_[i], exchangeAsset, rewardAmounts_[i], SWAP_REWARDS_PRICE_IMPACT_TOLERANCE ); } else { exchangeAssetBalanceBefore = 0; } } } uint exchangeAssetBalanceAfter = balance(exchangeAsset); earnedExchangeAsset = exchangeAssetBalanceAfter - exchangeAssetBalanceBefore; } function emitApr( IStrategy.StrategyBaseStorage storage $, address platform, address[] memory assets, uint[] memory amounts, uint tvl, uint totalBefore ) external { uint duration = block.timestamp - $.lastHardWork; IPriceReader priceReader = IPriceReader(IPlatform(platform).priceReader()); //slither-disable-next-line unused-return (uint earned,, uint[] memory assetPrices,) = priceReader.getAssetsPrice(assets, amounts); uint apr = computeApr(tvl, earned, duration); uint aprCompound = totalBefore != 0 ? computeApr(totalBefore, $.total - totalBefore, duration) : apr; uint sharePrice = tvl * 1e18 / IERC20($.vault).totalSupply(); emit IStrategy.HardWork(apr, aprCompound, earned, tvl, duration, sharePrice, assetPrices); $.lastApr = apr; $.lastAprCompound = aprCompound; $.lastHardWork = block.timestamp; } function balance(address token) public view returns (uint) { return IERC20(token).balanceOf(address(this)); } /// @dev https://www.investopedia.com/terms/a/apr.asp /// TVL and rewards should be in the same currency and with the same decimals function computeApr(uint tvl, uint earned, uint duration) public pure returns (uint) { if (tvl == 0 || duration == 0) { return 0; } return earned * 1e18 * ConstantsLib.DENOMINATOR * uint(365) / tvl / (duration * 1e18 / 1 days); } function assetsAmountsWithBalances( address[] memory assets_, uint[] memory amounts_ ) external view returns (address[] memory assets, uint[] memory amounts) { assets = assets_; amounts = amounts_; uint len = assets_.length; // nosemgrep for (uint i; i < len; ++i) { amounts[i] += balance(assets_[i]); } } function assetsAreOnBalance(address[] memory assets) external view returns (bool isReady) { uint rwLen = assets.length; for (uint i; i < rwLen; ++i) { if (IERC20(assets[i]).balanceOf(address(this)) > 0) { isReady = true; break; } } } // function getFarmsForStrategyId(address platform, string memory _id) external view returns (IFactory.Farm[] memory farms) { // uint total; // IFactory.Farm[] memory allFarms = IFactory(IPlatform(platform).factory()).farms(); // uint len = allFarms.length; // for (uint i; i < len; ++i) { // IFactory.Farm memory farm = allFarms[i]; // if (farm.status == 0 && CommonLib.eq(farm.strategyLogicId, _id)) { // total++; // } // } // farms = new IFactory.Farm[](total); // uint k; // for (uint i; i < len; ++i) { // IFactory.Farm memory farm = allFarms[i]; // if (farm.status == 0 && CommonLib.eq(farm.strategyLogicId, _id)) { // farms[k] = farm; // k++; // } // } // } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; library StrategyIdLib { string internal constant DEV = "Dev Alpha DeepSpaceSwap Farm"; string internal constant QUICKSWAPV3_STATIC_FARM = "QuickSwapV3 Static Farm"; string internal constant GAMMA_QUICKSWAP_MERKL_FARM = "Gamma QuickSwap Merkl Farm"; string internal constant GAMMA_RETRO_MERKL_FARM = "Gamma Retro Merkl Farm"; string internal constant GAMMA_UNISWAPV3_MERKL_FARM = "Gamma UniswapV3 Merkl Farm"; string internal constant COMPOUND_FARM = "Compound Farm"; string internal constant DEFIEDGE_QUICKSWAP_MERKL_FARM = "DefiEdge QuickSwap Merkl Farm"; string internal constant STEER_QUICKSWAP_MERKL_FARM = "Steer QuickSwap Merkl Farm"; string internal constant ICHI_QUICKSWAP_MERKL_FARM = "Ichi QuickSwap Merkl Farm"; string internal constant ICHI_RETRO_MERKL_FARM = "Ichi Retro Merkl Farm"; string internal constant QUICKSWAP_STATIC_MERKL_FARM = "QuickSwap Static Merkl Farm"; string internal constant CURVE_CONVEX_FARM = "Curve Convex Farm"; string internal constant YEARN = "Yearn"; string internal constant TRIDENT_PEARL_FARM = "Trident Pearl Farm"; string internal constant BEETS_STABLE_FARM = "Beets Stable Farm"; string internal constant BEETS_WEIGHTED_FARM = "Beets Weighted Farm"; string internal constant EQUALIZER_FARM = "Equalizer Farm"; string internal constant ICHI_SWAPX_FARM = "Ichi SwapX Farm"; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; library FarmMechanicsLib { string internal constant CLASSIC = "Classic"; string internal constant MERKL = "Merkl"; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import {IVolatilityOracle} from "../../integrations/algebrav4/IVolatilityOracle.sol"; import {UniswapV3MathLib} from "./UniswapV3MathLib.sol"; import {IAlgebraPool} from "../../integrations/algebrav4/IAlgebraPool.sol"; import {IAlgebraPoolErrors} from "../../integrations/algebrav4/pool/IAlgebraPoolErrors.sol"; library ISFLib { /// @notice Checks if the oracle is currently connected to the pool /// @param oracleAddress The address of oracle /// @param oracleAddress The address of the pool /// @return connected Whether or not the oracle is connected function isOracleConnectedToPool( address oracleAddress, address poolAddress ) internal view returns (bool connected) { if (oracleAddress == address(0)) { return false; } IAlgebraPool pool = IAlgebraPool(poolAddress); if (oracleAddress == pool.plugin()) { (,,, uint8 pluginConfig,,) = pool.globalState(); connected = hasFlag(pluginConfig, BEFORE_SWAP_FLAG); } } /// @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 (uint quoteAmount) { uint160 sqrtRatioX96 = UniswapV3MathLib.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint ratioX192 = uint(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? UniswapV3MathLib.mulDiv(ratioX192, baseAmount, 1 << 192) : UniswapV3MathLib.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint ratioX128 = UniswapV3MathLib.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? UniswapV3MathLib.mulDiv(ratioX128, baseAmount, 1 << 128) : UniswapV3MathLib.mulDiv(1 << 128, baseAmount, ratioX128); } } /// @notice Fetches time-weighted average tick using Algebra VolatilityOracle /// @param oracleAddress The address of oracle /// @param period Number of seconds in the past to start calculating time-weighted average /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp-period) to block.timestamp function consult(address oracleAddress, uint32 period) external view returns (int24 timeWeightedAverageTick) { require(period != 0, "Period is zero"); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; IVolatilityOracle oracle = IVolatilityOracle(oracleAddress); (int56[] memory tickCumulatives,) = oracle.getTimepoints(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / int56(uint56(period))); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(period)) != 0)) timeWeightedAverageTick--; } function hasFlag(uint8 pluginConfig, uint flag) internal pure returns (bool res) { assembly { res := gt(and(pluginConfig, flag), 0) } } function shouldReturn(bytes4 selector, bytes4 expectedSelector) internal pure { if (selector != expectedSelector) revert IAlgebraPoolErrors.invalidHookResponse(expectedSelector); } uint internal constant BEFORE_SWAP_FLAG = 1; uint internal constant AFTER_SWAP_FLAG = 1 << 1; uint internal constant BEFORE_POSITION_MODIFY_FLAG = 1 << 2; uint internal constant AFTER_POSITION_MODIFY_FLAG = 1 << 3; uint internal constant BEFORE_FLASH_FLAG = 1 << 4; uint internal constant AFTER_FLASH_FLAG = 1 << 5; uint internal constant AFTER_INIT_FLAG = 1 << 6; uint internal constant DYNAMIC_FEE = 1 << 7; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /// @notice Creating vaults, upgrading vaults and strategies, vault list, farms and strategy logics management /// @author Alien Deployer (https://github.com/a17) /// @author Jude (https://github.com/iammrjude) /// @author JodsMigel (https://github.com/JodsMigel) /// @author HCrypto7 (https://github.com/hcrypto7) interface IFactory { //region ----- Custom Errors ----- error VaultImplementationIsNotAvailable(); error VaultNotAllowedToDeploy(); error StrategyImplementationIsNotAvailable(); error StrategyLogicNotAllowedToDeploy(); error YouDontHaveEnoughTokens(uint userBalance, uint requireBalance, address payToken); error SuchVaultAlreadyDeployed(bytes32 key); error NotActiveVault(); error UpgradeDenied(bytes32 _hash); error AlreadyLastVersion(bytes32 _hash); error NotStrategy(); error BoostDurationTooLow(); error BoostAmountTooLow(); error BoostAmountIsZero(); //endregion ----- Custom Errors ----- //region ----- Events ----- event VaultAndStrategy( address indexed deployer, string vaultType, string strategyId, address vault, address strategy, string name, string symbol, address[] assets, bytes32 deploymentKey, uint vaultManagerTokenId ); event StrategyProxyUpgraded(address proxy, address oldImplementation, address newImplementation); event VaultProxyUpgraded(address proxy, address oldImplementation, address newImplementation); event VaultConfigChanged( string type_, address implementation, bool deployAllowed, bool upgradeAllowed, bool newVaultType ); event StrategyLogicConfigChanged( string id, address implementation, bool deployAllowed, bool upgradeAllowed, bool newStrategy ); event VaultStatus(address indexed vault, uint newStatus); event NewFarm(Farm[] farms); event UpdateFarm(uint id, Farm farm); event SetStrategyAvailableInitParams(string id, address[] initAddresses, uint[] initNums, int24[] initTicks); event AliasNameChanged(address indexed operator, address indexed tokenAddress, string newAliasName); //endregion -- Events ----- //region ----- Data types ----- /// @custom:storage-location erc7201:stability.Factory struct FactoryStorage { /// @inheritdoc IFactory mapping(bytes32 typeHash => VaultConfig) vaultConfig; /// @inheritdoc IFactory mapping(bytes32 idHash => StrategyLogicConfig) strategyLogicConfig; /// @inheritdoc IFactory mapping(bytes32 deploymentKey => address vaultProxy) deploymentKey; /// @inheritdoc IFactory mapping(address vault => uint status) vaultStatus; /// @inheritdoc IFactory mapping(address address_ => bool isStrategy_) isStrategy; EnumerableSet.Bytes32Set vaultTypeHashes; EnumerableSet.Bytes32Set strategyLogicIdHashes; mapping(uint week => mapping(uint builderPermitTokenId => uint vaultsBuilt)) vaultsBuiltByPermitTokenId; address[] deployedVaults; Farm[] farms; /// @inheritdoc IFactory mapping(bytes32 idHash => StrategyAvailableInitParams) strategyAvailableInitParams; mapping(address tokenAddress => string aliasName) aliasNames; } struct VaultConfig { string vaultType; address implementation; bool deployAllowed; bool upgradeAllowed; uint buildingPrice; } struct StrategyLogicConfig { string id; address implementation; bool deployAllowed; bool upgradeAllowed; bool farming; uint tokenId; } struct Farm { uint status; address pool; string strategyLogicId; address[] rewardAssets; address[] addresses; uint[] nums; int24[] ticks; } struct StrategyAvailableInitParams { address[] initAddresses; uint[] initNums; int24[] initTicks; } //endregion -- Data types ----- //region ----- View functions ----- /// @notice All vaults deployed by the factory /// @return Vault proxy addresses function deployedVaults() external view returns (address[] memory); /// @notice Total vaults deployed function deployedVaultsLength() external view returns (uint); /// @notice Get vault by VaultManager tokenId /// @param id Vault array index. Same as tokenId of VaultManager NFT /// @return Address of VaultProxy function deployedVault(uint id) external view returns (address); /// @notice All farms known by the factory in current network function farms() external view returns (Farm[] memory); /// @notice Total farms known by the factory in current network function farmsLength() external view returns (uint); /// @notice Farm data by farm index /// @param id Index of farm function farm(uint id) external view returns (Farm memory); /// @notice Strategy logic settings /// @param idHash keccak256 hash of strategy logic string ID /// @return config Strategy logic settings function strategyLogicConfig(bytes32 idHash) external view returns (StrategyLogicConfig memory config); /// @notice All known strategies /// @return Array of keccak256 hashes of strategy logic string ID function strategyLogicIdHashes() external view returns (bytes32[] memory); // todo remove, use new function without calculating vault symbol on the fly for not initialized vaults // factory required that special functionally only internally, not for interface function getStrategyData( string memory vaultType, address strategyAddress, address bbAsset ) external view returns ( string memory strategyId, address[] memory assets, string[] memory assetsSymbols, string memory specificName, string memory vaultSymbol ); /// @dev Get best asset of assets to be strategy exchange asset function getExchangeAssetIndex(address[] memory assets) external view returns (uint); /// @notice Deployment key of created vault /// @param deploymentKey_ Hash of concatenated unique vault and strategy initialization parameters /// @return Address of deployed vault function deploymentKey(bytes32 deploymentKey_) external view returns (address); /// @notice Calculating deployment key based on unique vault and strategy initialization parameters /// @param vaultType Vault type string /// @param strategyId Strategy logic Id string /// @param vaultInitAddresses Vault initizlization addresses for deployVaultAndStrategy method /// @param vaultInitNums Vault initizlization uint numbers for deployVaultAndStrategy method /// @param strategyInitAddresses Strategy initizlization addresses for deployVaultAndStrategy method /// @param strategyInitNums Strategy initizlization uint numbers for deployVaultAndStrategy method /// @param strategyInitTicks Strategy initizlization int24 ticks for deployVaultAndStrategy method function getDeploymentKey( string memory vaultType, string memory strategyId, address[] memory vaultInitAddresses, uint[] memory vaultInitNums, address[] memory strategyInitAddresses, uint[] memory strategyInitNums, int24[] memory strategyInitTicks ) external returns (bytes32); /// @notice Available variants of new vault for creating. /// The structure of the function's output values is complex, /// but after parsing them, the front end has all the data to generate a list of vaults to create. /// @return desc Descriptions of the strategy for making money /// @return vaultType Vault type strings. Output values are matched by index with previous array. /// @return strategyId Strategy logic ID strings. Output values are matched by index with previous array. /// @return initIndexes Map of start and end indexes in next 5 arrays. Output values are matched by index with previous array. /// [0] Start index in vaultInitAddresses /// [1] End index in vaultInitAddresses /// [2] Start index in vaultInitNums /// [3] End index in vaultInitNums /// [4] Start index in strategyInitAddresses /// [5] End index in strategyInitAddresses /// [6] Start index in strategyInitNums /// [7] End index in strategyInitNums /// [8] Start index in strategyInitTicks /// [9] End index in strategyInitTicks /// @return vaultInitAddresses Vault initizlization addresses for deployVaultAndStrategy method for all building variants. /// @return vaultInitNums Vault initizlization uint numbers for deployVaultAndStrategy method for all building variants. /// @return strategyInitAddresses Strategy initizlization addresses for deployVaultAndStrategy method for all building variants. /// @return strategyInitNums Strategy initizlization uint numbers for deployVaultAndStrategy method for all building variants. /// @return strategyInitTicks Strategy initizlization int24 ticks for deployVaultAndStrategy method for all building variants. function whatToBuild() external view returns ( string[] memory desc, string[] memory vaultType, string[] memory strategyId, uint[10][] memory initIndexes, address[] memory vaultInitAddresses, uint[] memory vaultInitNums, address[] memory strategyInitAddresses, uint[] memory strategyInitNums, int24[] memory strategyInitTicks ); /// @notice Governance and multisig can set a vault status other than Active - the default status. /// HardWorker only works with active vaults. /// @return status Constant from VaultStatusLib function vaultStatus(address vault) external view returns (uint status); /// @notice Check that strategy proxy deployed by the Factory /// @param address_ Address of contract /// @return This address is our strategy proxy function isStrategy(address address_) external view returns (bool); /// @notice How much vaults was built by builderPermitToken NFT tokenId in week /// @param week Week index (timestamp / (86400 * 7)) /// @param builderPermitTokenId Token ID of buildingPermitToken NFT /// @return vaultsBuilt Vaults built function vaultsBuiltByPermitTokenId( uint week, uint builderPermitTokenId ) external view returns (uint vaultsBuilt); /// @notice Data on all factory strategies. /// The output values are matched by index in the arrays. /// @return id Strategy logic ID strings /// @return deployAllowed New vaults can be deployed /// @return upgradeAllowed Strategy can be upgraded /// @return farming It is farming strategy (earns farming/gauge rewards) /// @return tokenId Token ID of StrategyLogic NFT /// @return tokenURI StrategyLogic NFT tokenId metadata and on-chain image /// @return extra Strategy color, background color and other extra data function strategies() external view returns ( string[] memory id, bool[] memory deployAllowed, bool[] memory upgradeAllowed, bool[] memory farming, uint[] memory tokenId, string[] memory tokenURI, bytes32[] memory extra ); /// @notice Get config of vault type /// @param typeHash Keccak256 hash of vault type string /// @return vaultType Vault type string /// @return implementation Vault implementation address /// @return deployAllowed New vaults can be deployed /// @return upgradeAllowed Vaults can be upgraded /// @return buildingPrice Price of building new vault function vaultConfig(bytes32 typeHash) external view returns ( string memory vaultType, address implementation, bool deployAllowed, bool upgradeAllowed, uint buildingPrice ); /// @notice Data on all factory vault types /// The output values are matched by index in the arrays. /// @return vaultType Vault type string /// @return implementation Address of vault implemented logic /// @return deployAllowed New vaults can be deployed /// @return upgradeAllowed Vaults can be upgraded /// @return buildingPrice Price of building new vault /// @return extra Vault type color, background color and other extra data function vaultTypes() external view returns ( string[] memory vaultType, address[] memory implementation, bool[] memory deployAllowed, bool[] memory upgradeAllowed, uint[] memory buildingPrice, bytes32[] memory extra ); /// @notice Initialization strategy params store function strategyAvailableInitParams(bytes32 idHash) external view returns (StrategyAvailableInitParams memory); /// @notice Retrieves the alias name associated with a given address /// @param tokenAddress_ The address to query for its alias name /// @return The alias name associated with the provided address function getAliasName(address tokenAddress_) external view returns (string memory); //endregion -- View functions ----- //region ----- Write functions ----- /// @notice Main method of the Factory - new vault creation by user. /// @param vaultType Vault type ID string /// @param strategyId Strategy logic ID string /// Different types of vaults and strategies have different lengths of input arrays. /// @param vaultInitAddresses Addresses for vault initialization /// @param vaultInitNums Numbers for vault initialization /// @param strategyInitAddresses Addresses for strategy initialization /// @param strategyInitNums Numbers for strategy initialization /// @param strategyInitTicks Ticks for strategy initialization /// @return vault Deployed VaultProxy address /// @return strategy Deployed StrategyProxy address function deployVaultAndStrategy( string memory vaultType, string memory strategyId, address[] memory vaultInitAddresses, uint[] memory vaultInitNums, address[] memory strategyInitAddresses, uint[] memory strategyInitNums, int24[] memory strategyInitTicks ) external returns (address vault, address strategy); /// @notice Upgrade vault proxy. Can be called by any address. /// @param vault Address of vault proxy for upgrade function upgradeVaultProxy(address vault) external; /// @notice Upgrade strategy proxy. Can be called by any address. /// @param strategy Address of strategy proxy for upgrade function upgradeStrategyProxy(address strategy) external; /// @notice Add farm to factory /// @param farms_ Settings and data required to work with the farm. function addFarms(Farm[] memory farms_) external; /// @notice Update farm /// @param id Farm index /// @param farm_ Settings and data required to work with the farm. function updateFarm(uint id, Farm memory farm_) external; /// @notice Initial addition or change of vault type settings. /// Operator can add new vault type. Governance or multisig can change existing vault type config. /// @param vaultConfig_ Vault type settings function setVaultConfig(VaultConfig memory vaultConfig_) external; /// @notice Initial addition or change of strategy logic settings. /// Operator can add new strategy logic. Governance or multisig can change existing logic config. /// @param config Strategy logic settings /// @param developer Strategy developer is receiver of minted StrategyLogic NFT on initial addition function setStrategyLogicConfig(StrategyLogicConfig memory config, address developer) external; /// @notice Governance and multisig can set a vault status other than Active - the default status. /// @param vaults Addresses of vault proxy /// @param statuses New vault statuses. Constant from VaultStatusLib function setVaultStatus(address[] memory vaults, uint[] memory statuses) external; /// @notice Initial addition or change of strategy available init params /// @param id Strategy ID string /// @param initParams Init params variations that will be parsed by strategy function setStrategyAvailableInitParams(string memory id, StrategyAvailableInitParams memory initParams) external; /// @notice Assigns a new alias name to a specific address /// @dev This function may require certain permissions to be called successfully. /// @param tokenAddress_ The address to assign an alias name to /// @param aliasName_ The alias name to assign to the given address function setAliasName(address tokenAddress_, string memory aliasName_) external; //endregion -- Write functions ----- }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @dev Get price, swap, liquidity calculations. Used by strategies and swapper /// @author Alien Deployer (https://github.com/a17) /// @author JodsMigel (https://github.com/JodsMigel) interface IAmmAdapter is IERC165 { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error PriceIncreased(); error WrongCallbackAmount(); error NotSupportedByCAMM(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ event SwapInPool( address pool, address tokenIn, address tokenOut, address recipient, uint priceImpactTolerance, uint amountIn, uint amountOut ); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DATA TYPES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ struct SwapCallbackData { address tokenIn; uint amount; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice String ID of the adapter function ammAdapterId() external view returns (string memory); /// @notice Tokens of a pool supported by the adapter function poolTokens(address pool) external view returns (address[] memory); /// @notice Computes the maximum amount of liquidity received for given amounts of pool assets and the current /// pool price. /// This function signature can be used only for non-concentrated AMMs. /// @param pool Address of a pool supported by the adapter /// @param amounts Amounts of pool assets /// @return liquidity Liquidity out value /// @return amountsConsumed Amounts of consumed assets when providing liquidity function getLiquidityForAmounts( address pool, uint[] memory amounts ) external view returns (uint liquidity, uint[] memory amountsConsumed); /// @notice Priced proportions of pool assets /// @param pool Address of a pool supported by the adapter /// @return Proportions with 18 decimals precision. Max is 1e18, min is 0. function getProportions(address pool) external view returns (uint[] memory); /// @notice Current price in pool without amount impact /// @param pool Address of a pool supported by the adapter /// @param tokenIn Token for sell /// @param tokenOut Token for buy /// @param amount Amount of tokenIn. For zero value provided amount 1.0 (10 ** decimals of tokenIn) will be used. /// @return Amount of tokenOut with tokenOut decimals precision function getPrice(address pool, address tokenIn, address tokenOut, uint amount) external view returns (uint); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* WRITE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Swap given tokenIn for tokenOut. Assume that tokenIn already sent to this contract. /// @param pool Address of a pool supported by the adapter /// @param tokenIn Token for sell /// @param tokenOut Token for buy /// @param recipient Recipient for tokenOut /// @param priceImpactTolerance Price impact tolerance. Must include fees at least. Denominator is 100_000. function swap( address pool, address tokenIn, address tokenOut, address recipient, uint priceImpactTolerance ) external; /// @dev Initializer for proxied adapter function init(address platform) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.22; import "./IAmmAdapter.sol"; /// @dev Adapter for interacting with Concentrated Automated Market Make /// based on liquidity pool of 2 tokens. /// @author Alien Deployer (https://github.com/a17) interface ICAmmAdapter is IAmmAdapter { /// @notice Price in pool at specified tick /// @param pool Address of a pool supported by the adapter /// @param tokenIn Token for sell /// @return Output amount of swap 1.0 tokenIn in pool without price impact function getPriceAtTick(address pool, address tokenIn, int24 tick) external view returns (uint); /// @notice Priced proportions of pool assets in specified range /// @param pool Address of a pool supported by the adapter /// @param ticks Tick boundaries. Lower and upper ticks for UniswapV3-like AMM position. /// @return Proportions with 5 decimals precision. Max is 100_000, min is 0. function getProportions(address pool, int24[] memory ticks) external view returns (uint[] memory); /// @notice Computes the maximum amount of liquidity received for given amounts of pool assets and the current /// pool prices and the prices at the tick boundaries /// @param pool Address of a pool supported by the adapter /// @param amounts Ampunts of pool assets /// @param ticks Tick boundaries. Lower and upper ticks for UniswapV3-like AMM position. /// @return liquidity Liquidity out value /// @return amountsConsumed Amounts of consumed assets of provided liquidity function getLiquidityForAmounts( address pool, uint[] memory amounts, int24[] memory ticks ) external view returns (uint liquidity, uint[] memory amountsConsumed); /// @notice Computes pool assets amounts for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param pool Address of a pool supported by the adapter /// @param ticks Tick boundaries. Lower and upper ticks for UniswapV3-like AMM position. /// @param liquidity Liquidity value /// @return amounts Amounts out of provided liquidity function getAmountsForLiquidity( address pool, int24[] memory ticks, uint128 liquidity ) external view returns (uint[] memory amounts); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @dev Core interface of strategy logic interface IStrategy is IERC165 { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ event HardWork( uint apr, uint compoundApr, uint earned, uint tvl, uint duration, uint sharePrice, uint[] assetPrices ); event ExtractFees( uint vaultManagerReceiverFee, uint strategyLogicReceiverFee, uint ecosystemRevenueReceiverFee, uint multisigReceiverFee ); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error NotReadyForHardWork(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DATA TYPES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @custom:storage-location erc7201:stability.StrategyBase struct StrategyBaseStorage { /// @inheritdoc IStrategy address vault; /// @inheritdoc IStrategy uint total; /// @inheritdoc IStrategy uint lastHardWork; /// @inheritdoc IStrategy uint lastApr; /// @inheritdoc IStrategy uint lastAprCompound; /// @inheritdoc IStrategy address[] _assets; /// @inheritdoc IStrategy address _underlying; string _id; uint _exchangeAssetIndex; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Strategy logic string ID function strategyLogicId() external view returns (string memory); /// @dev Extra data /// @return 0-2 bytes - strategy color /// 3-5 bytes - strategy background color /// 6-31 bytes - free function extra() external view returns (bytes32); /// @dev Types of vault that supported by strategy implementation /// @return types Vault type ID strings function supportedVaultTypes() external view returns (string[] memory types); /// @dev Linked vault address function vault() external view returns (address); /// @dev Final assets that strategy invests function assets() external view returns (address[] memory); /// @notice Final assets and amounts that strategy manages function assetsAmounts() external view returns (address[] memory assets_, uint[] memory amounts_); /// @notice Priced invested assets proportions /// @return proportions Proportions of assets with 18 decimals. Min is 0, max is 1e18. function getAssetsProportions() external view returns (uint[] memory proportions); /// @notice Underlying token address /// @dev Can be used for liquidity farming strategies where AMM has fungible liquidity token (Solidly forks, etc), /// for concentrated liquidity tokenized vaults (Gamma, G-UNI etc) and for other needs. /// @return Address of underlying token or zero address if no underlying in strategy function underlying() external view returns (address); /// @dev Balance of liquidity token or liquidity value function total() external view returns (uint); /// @dev Last HardWork time /// @return Timestamp function lastHardWork() external view returns (uint); /// @dev Last APR of earned USD amount registered by HardWork /// ONLY FOR OFF-CHAIN USE. /// Not trusted asset price can be manipulated. /// @return APR with 18 decimals. 1e18 - 100%. function lastApr() external view returns (uint); /// @dev Last APR of compounded assets registered by HardWork. /// Can be used on-chain. /// @return APR with 18 decimals. 1e18 - 100%. function lastAprCompound() external view returns (uint); /// @notice Calculation of consumed amounts and liquidity/underlying value for provided strategy assets and amounts. /// @param assets_ Strategy assets or part of them, if necessary /// @param amountsMax Amounts of specified assets available for investing /// @return amountsConsumed Cosumed amounts of assets when investing /// @return value Liquidity value or underlying token amount minted when investing function previewDepositAssets( address[] memory assets_, uint[] memory amountsMax ) external view returns (uint[] memory amountsConsumed, uint value); /// @notice Write version of previewDepositAssets /// @param assets_ Strategy assets or part of them, if necessary /// @param amountsMax Amounts of specified assets available for investing /// @return amountsConsumed Cosumed amounts of assets when investing /// @return value Liquidity value or underlying token amount minted when investing function previewDepositAssetsWrite( address[] memory assets_, uint[] memory amountsMax ) external returns (uint[] memory amountsConsumed, uint value); /// @notice All strategy revenue (pool fees, farm rewards etc) that not claimed by strategy yet /// @return assets_ Revenue assets /// @return amounts Amounts. Index of asset same as in previous array. function getRevenue() external view returns (address[] memory assets_, uint[] memory amounts); /// @notice Optional specific name of investing strategy, underyling type, setup variation etc /// @return name Empty string or specific name /// @return showInVaultSymbol Show specific in linked vault symbol function getSpecificName() external view returns (string memory name, bool showInVaultSymbol); /// @notice Variants pf strategy initializations with description of money making mechanic. /// As example, if strategy need farm, then number of variations is number of available farms. /// If CAMM strategy have set of available widths (tick ranges), then number of variations is number of available farms. /// If both example conditions are met then total number or variations = total farms * total widths. /// @param platform_ Need this param because method called when strategy implementation is not initialized /// @return variants Descriptions of the strategy for making money /// @return addresses Init strategy addresses. Indexes for each variants depends of copmpared arrays lengths. /// @return nums Init strategy numbers. Indexes for each variants depends of copmpared arrays lengths. /// @return ticks Init strategy ticks. Indexes for each variants depends of copmpared arrays lengths. function initVariants(address platform_) external view returns (string[] memory variants, address[] memory addresses, uint[] memory nums, int24[] memory ticks); /// @notice How does the strategy make money? /// @return Description in free form function description() external view returns (string memory); /// @notice Is HardWork on vault deposits can be enabled function isHardWorkOnDepositAllowed() external view returns (bool); /// @notice Is HardWork can be executed function isReadyForHardWork() external view returns (bool); /// @notice Strategy not need to process revenue on HardWorks function autoCompoundingByUnderlyingProtocol() external view returns (bool); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* WRITE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev A single universal initializer for all strategy implementations. /// @param addresses All addresses that strategy requires for initialization. Min array length is 2. /// addresses[0]: platform (required) /// addresses[1]: vault (required) /// addresses[2]: initStrategyAddresses[0] (optional) /// addresses[3]: initStrategyAddresses[1] (optional) /// addresses[n]: initStrategyAddresses[n - 2] (optional) /// @param nums All uint values that strategy requires for initialization. Min array length is 0. /// @param ticks All int24 values that strategy requires for initialization. Min array length is 0. function initialize(address[] memory addresses, uint[] memory nums, int24[] memory ticks) external; /// @notice Invest strategy assets. Amounts of assets must be already on strategy contract balance. /// Only vault can call this. /// @param amounts Anounts of strategy assets /// @return value Liquidity value or underlying token amount function depositAssets(uint[] memory amounts) external returns (uint value); /// @notice Invest underlying asset. Asset must be already on strategy contract balance. /// Only vault can call this. /// @param amount Amount of underlying asset to invest /// @return amountsConsumed Cosumed amounts of invested assets function depositUnderlying(uint amount) external returns (uint[] memory amountsConsumed); /// @dev For specified amount of shares and assets_, withdraw strategy assets from farm/pool/staking and send to receiver if possible /// Only vault can call this. /// @param assets_ Here we give the user a choice of assets to withdraw if strategy support it /// @param value Part of strategy total value to withdraw /// @param receiver User address /// @return amountsOut Amounts of assets sent to user function withdrawAssets( address[] memory assets_, uint value, address receiver ) external returns (uint[] memory amountsOut); /// @notice Wothdraw underlying invested and send to receiver /// Only vault can call this. /// @param amount Ampunt of underlying asset to withdraw /// @param receiver User of vault which withdraw underlying from the vault function withdrawUnderlying(uint amount, address receiver) external; /// @dev For specified amount of shares, transfer strategy assets from contract balance and send to receiver if possible /// This method is called by vault w/o underlying on triggered fuse mode. /// Only vault can call this. /// @param amount Ampunt of liquidity value that user withdraw /// @param totalAmount Total amount of strategy liquidity /// @param receiver User of vault which withdraw assets /// @return amountsOut Amounts of strategy assets sent to user function transferAssets( uint amount, uint totalAmount, address receiver ) external returns (uint[] memory amountsOut); /// @notice Execute HardWork /// During HardWork strategy claiming revenue and processing it. /// Only vault can call this. function doHardWork() external; /// @notice Emergency stop investing by strategy, withdraw liquidity without rewards. /// This action triggers FUSE mode. /// Only governance or multisig can call this. function emergencyStopInvesting() external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; /// @dev Mostly this interface need for front-end and tests for interacting with farming strategies /// @author JodsMigel (https://github.com/JodsMigel) interface IFarmingStrategy { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ event RewardsClaimed(uint[] amounts); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error BadFarm(); error IncorrectStrategyId(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DATA TYPES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @custom:storage-location erc7201:stability.FarmingStrategyBase struct FarmingStrategyBaseStorage { /// @inheritdoc IFarmingStrategy uint farmId; address[] _rewardAssets; uint[] _rewardsOnBalance; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Index of the farm used by initialized strategy function farmId() external view returns (uint); /// @notice Strategy can earn money on farm now /// Some strategies can continue work and earn pool fees after ending of farm rewards. function canFarm() external view returns (bool); /// @notice Mechanics of receiving farming rewards function farmMechanics() external view returns (string memory); /// @notice Farming reward assets for claim and liquidate /// @return Addresses of farm reward ERC20 tokens function farmingAssets() external view returns (address[] memory); /// @notice Address of pool for staking asset/underlying function stakingPool() external view returns (address); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* WRITE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Update strategy farming reward assets from Factory /// Only operator can call this function refreshFarmingAssets() external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "../interfaces/IAmmAdapter.sol"; /// @title Liquidity providing strategy /// @author Alien Deployer (https://github.com/a17) interface ILPStrategy { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ event FeesClaimed(uint[] fees); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error ZeroAmmAdapter(); error IncorrectAssetsLength(); error IncorrectAssets(); error IncorrectAmountsLength(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DATA TYPES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @custom:storage-location erc7201:stability.LPStrategyBase struct LPStrategyBaseStorage { /// @inheritdoc ILPStrategy address pool; /// @inheritdoc ILPStrategy IAmmAdapter ammAdapter; uint[] _feesOnBalance; } struct LPStrategyBaseInitParams { string id; address platform; address vault; address pool; address underlying; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev AMM adapter string ID for interacting with pool function ammAdapterId() external view returns (string memory); /// @dev AMM adapter address for interacting with pool function ammAdapter() external view returns (IAmmAdapter); /// @dev AMM function pool() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; /// @dev Base core interface implemented by most platform contracts. /// Inherited contracts store an immutable Platform proxy address in the storage, /// which provides authorization capabilities and infrastructure contract addresses. /// @author Alien Deployer (https://github.com/a17) /// @author JodsMigel (https://github.com/JodsMigel) interface IControllable { //region ----- Custom Errors ----- error IncorrectZeroArgument(); error IncorrectMsgSender(); error NotGovernance(); error NotMultisig(); error NotGovernanceAndNotMultisig(); error NotOperator(); error NotFactory(); error NotPlatform(); error NotVault(); error IncorrectArrayLength(); error AlreadyExist(); error NotExist(); error NotTheOwner(); error ETHTransferFailed(); error IncorrectInitParams(); //endregion -- Custom Errors ----- event ContractInitialized(address platform, uint ts, uint block); /// @notice Stability Platform main contract address function platform() external view returns (address); /// @notice Version of contract implementation /// @dev SemVer scheme MAJOR.MINOR.PATCH //slither-disable-next-line naming-convention function VERSION() external view returns (string memory); /// @notice Block number when contract was initialized function createdBlock() external view returns (uint); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; /// @notice Interface of the main contract and entry point to the platform. /// @author Alien Deployer (https://github.com/a17) /// @author Jude (https://github.com/iammrjude) /// @author JodsMigel (https://github.com/JodsMigel) interface IPlatform { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error AlreadyAnnounced(); error SameVersion(); error NoNewVersion(); error UpgradeTimerIsNotOver(uint TimerTimestamp); error IncorrectFee(uint minFee, uint maxFee); error NotEnoughAllowedBBToken(); error TokenAlreadyExistsInSet(address token); error AggregatorNotExists(address dexAggRouter); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ event PlatformVersion(string version); event UpgradeAnnounce( string oldVersion, string newVersion, address[] proxies, address[] newImplementations, uint timelock ); event CancelUpgrade(string oldVersion, string newVersion); event ProxyUpgraded( address indexed proxy, address implementation, string oldContractVersion, string newContractVersion ); event Addresses( address multisig_, address factory_, address priceReader_, address swapper_, address buildingPermitToken_, address vaultManager_, address strategyLogic_, address aprOracle_, address hardWorker, address rebalancer, address zap, address bridge ); event OperatorAdded(address operator); event OperatorRemoved(address operator); event FeesChanged(uint fee, uint feeShareVaultManager, uint feeShareStrategyLogic, uint feeShareEcosystem); event MinInitialBoostChanged(uint minInitialBoostPerDay, uint minInitialBoostDuration); event NewAmmAdapter(string id, address proxy); event EcosystemRevenueReceiver(address receiver); event SetAllowedBBTokenVaults(address bbToken, uint vaultsToBuild, bool firstSet); event RemoveAllowedBBToken(address bbToken); event AddAllowedBoostRewardToken(address token); event RemoveAllowedBoostRewardToken(address token); event AddDefaultBoostRewardToken(address token); event RemoveDefaultBoostRewardToken(address token); event AddBoostTokens(address[] allowedBoostRewardToken, address[] defaultBoostRewardToken); event AllowedBBTokenVaultUsed(address bbToken, uint vaultToUse); event AddDexAggregator(address router); event RemoveDexAggregator(address router); event MinTvlForFreeHardWorkChanged(uint oldValue, uint newValue); event CustomVaultFee(address vault, uint platformFee); event Rebalancer(address rebalancer_); event Bridge(address bridge_); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DATA TYPES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ struct PlatformUpgrade { string newVersion; address[] proxies; address[] newImplementations; } struct PlatformSettings { string networkName; bytes32 networkExtra; uint fee; uint feeShareVaultManager; uint feeShareStrategyLogic; uint feeShareEcosystem; uint minInitialBoostPerDay; uint minInitialBoostDuration; } struct AmmAdapter { string id; address proxy; } struct SetupAddresses { address factory; address priceReader; address swapper; address buildingPermitToken; address buildingPayPerVaultToken; address vaultManager; address strategyLogic; address aprOracle; address targetExchangeAsset; address hardWorker; address zap; address bridge; address rebalancer; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Platform version in CalVer scheme: YY.MM.MINOR-tag. Updates on core contract upgrades. function platformVersion() external view returns (string memory); /// @notice Time delay for proxy upgrades of core contracts and changing important platform settings by multisig //slither-disable-next-line naming-convention function TIME_LOCK() external view returns (uint); /// @notice DAO governance function governance() external view returns (address); /// @notice Core team multi signature wallet. Development and operations fund function multisig() external view returns (address); /// @notice This NFT allow user to build limited number of vaults per week function buildingPermitToken() external view returns (address); /// @notice This ERC20 token is used as payment token for vault building function buildingPayPerVaultToken() external view returns (address); /// @notice Receiver of ecosystem revenue function ecosystemRevenueReceiver() external view returns (address); /// @dev The best asset in a network for swaps between strategy assets and farms rewards assets /// The target exchange asset is used for finding the best strategy's exchange asset. /// Rhe fewer routes needed to swap to the target exchange asset, the better. function targetExchangeAsset() external view returns (address); /// @notice Platform factory assembling vaults. Stores settings, strategy logic, farms. /// Provides the opportunity to upgrade vaults and strategies. /// @return Address of Factory proxy function factory() external view returns (address); /// @notice The holders of these NFT receive a share of the vault revenue /// @return Address of VaultManager proxy function vaultManager() external view returns (address); /// @notice The holders of these tokens receive a share of the revenue received in all vaults using this strategy logic. function strategyLogic() external view returns (address); /// @notice Combining oracle and DeX spot prices /// @return Address of PriceReader proxy function priceReader() external view returns (address); /// @notice Providing underlying assets APRs on-chain /// @return Address of AprOracle proxy function aprOracle() external view returns (address); /// @notice On-chain price quoter and swapper /// @return Address of Swapper proxy function swapper() external view returns (address); /// @notice HardWork resolver and caller /// @return Address of HardWorker proxy function hardWorker() external view returns (address); /// @notice Rebalance resolver /// @return Address of Rebalancer proxy function rebalancer() external view returns (address); /// @notice ZAP feature /// @return Address of Zap proxy function zap() external view returns (address); /// @notice Stability Bridge /// @return Address of Bridge proxy function bridge() external view returns (address); /// @notice Name of current EVM network function networkName() external view returns (string memory); /// @notice Minimal initial boost rewards per day USD amount which needs to create rewarding vault function minInitialBoostPerDay() external view returns (uint); /// @notice Minimal boost rewards vesting duration for initial boost function minInitialBoostDuration() external view returns (uint); /// @notice This function provides the timestamp of the platform upgrade timelock. /// @dev This function is an external view function, meaning it doesn't modify the state. /// @return uint representing the timestamp of the platform upgrade timelock. function platformUpgradeTimelock() external view returns (uint); /// @dev Extra network data /// @return 0-2 bytes - color /// 3-5 bytes - background color /// 6-31 bytes - free function networkExtra() external view returns (bytes32); /// @notice Pending platform upgrade data function pendingPlatformUpgrade() external view returns (PlatformUpgrade memory); /// @notice Get platform revenue fee settings /// @return fee Revenue fee % (between MIN_FEE - MAX_FEE) with DENOMINATOR precision. /// @return feeShareVaultManager Revenue fee share % of VaultManager tokenId owner /// @return feeShareStrategyLogic Revenue fee share % of StrategyLogic tokenId owner /// @return feeShareEcosystem Revenue fee share % of ecosystemFeeReceiver function getFees() external view returns (uint fee, uint feeShareVaultManager, uint feeShareStrategyLogic, uint feeShareEcosystem); /// @notice Get custom vault platform fee /// @return fee revenue fee % with DENOMINATOR precision function getCustomVaultFee(address vault) external view returns (uint fee); /// @notice Platform settings function getPlatformSettings() external view returns (PlatformSettings memory); /// @notice AMM adapters of the platform function getAmmAdapters() external view returns (string[] memory id, address[] memory proxy); /// @notice Get AMM adapter data by hash /// @param ammAdapterIdHash Keccak256 hash of adapter ID string /// @return ID string and proxy address of AMM adapter function ammAdapter(bytes32 ammAdapterIdHash) external view returns (AmmAdapter memory); /// @notice Allowed buy-back tokens for rewarding vaults function allowedBBTokens() external view returns (address[] memory); /// @notice Vaults building limit for buy-back token. /// This limit decrements when a vault for BB-token is built. /// @param token Allowed buy-back token /// @return vaultsLimit Number of vaults that can be built for BB-token function allowedBBTokenVaults(address token) external view returns (uint vaultsLimit); /// @notice Vaults building limits for allowed buy-back tokens. /// @return bbToken Allowed buy-back tokens /// @return vaultsLimit Number of vaults that can be built for BB-tokens function allowedBBTokenVaults() external view returns (address[] memory bbToken, uint[] memory vaultsLimit); /// @notice Non-zero vaults building limits for allowed buy-back tokens. /// @return bbToken Allowed buy-back tokens /// @return vaultsLimit Number of vaults that can be built for BB-tokens function allowedBBTokenVaultsFiltered() external view returns (address[] memory bbToken, uint[] memory vaultsLimit); /// @notice Check address for existance in operators list /// @param operator Address /// @return True if this address is Stability Operator function isOperator(address operator) external view returns (bool); /// @notice Tokens that can be used for boost rewards of rewarding vaults /// @return Addresses of tokens function allowedBoostRewardTokens() external view returns (address[] memory); /// @notice Allowed boost reward tokens that used for unmanaged rewarding vaults creation /// @return Addresses of tokens function defaultBoostRewardTokens() external view returns (address[] memory); /// @notice Allowed boost reward tokens that used for unmanaged rewarding vaults creation /// @param addressToRemove This address will be removed from default boost reward tokens /// @return Addresses of tokens function defaultBoostRewardTokensFiltered(address addressToRemove) external view returns (address[] memory); /// @notice Allowed DeX aggregators /// @return Addresses of DeX aggregator rounters function dexAggregators() external view returns (address[] memory); /// @notice DeX aggregator router address is allowed to be used in the platform /// @param dexAggRouter Address of DeX aggreagator router /// @return Can be used function isAllowedDexAggregatorRouter(address dexAggRouter) external view returns (bool); /// @notice Show minimum TVL for compensate if vault has not enough ETH /// @return Minimum TVL for compensate. function minTvlForFreeHardWork() external view returns (uint); /// @notice Front-end platform viewer /// @return platformAddresses Platform core addresses /// platformAddresses[0] factory /// platformAddresses[1] vaultManager /// platformAddresses[2] strategyLogic /// platformAddresses[3] buildingPermitToken /// platformAddresses[4] buildingPayPerVaultToken /// platformAddresses[5] governance /// platformAddresses[6] multisig /// platformAddresses[7] zap /// platformAddresses[8] bridge /// @return bcAssets Blue chip token addresses /// @return dexAggregators_ DeX aggregators allowed to be used entire the platform /// @return vaultType Vault type ID strings /// @return vaultExtra Vault color, background color and other extra data. Index of vault same as in previous array. /// @return vaultBulldingPrice Price of creating new vault in buildingPayPerVaultToken. Index of vault same as in previous array. /// @return strategyId Strategy logic ID strings /// @return isFarmingStrategy True if strategy is farming strategy. Index of strategy same as in previous array. /// @return strategyTokenURI StrategyLogic NFT tokenId metadata and on-chain image. Index of strategy same as in previous array. /// @return strategyExtra Strategy color, background color and other extra data. Index of strategy same as in previous array. function getData() external view returns ( address[] memory platformAddresses, address[] memory bcAssets, address[] memory dexAggregators_, string[] memory vaultType, bytes32[] memory vaultExtra, uint[] memory vaultBulldingPrice, string[] memory strategyId, bool[] memory isFarmingStrategy, string[] memory strategyTokenURI, bytes32[] memory strategyExtra ); // todo add vaultSymbol, vaultName /// @notice Front-end balances, prices and vault list viewer /// @param yourAccount Address of account to query balances /// @return token Tokens supported by the platform /// @return tokenPrice USD price of token. Index of token same as in previous array. /// @return tokenUserBalance User balance of token. Index of token same as in previous array. /// @return vault Deployed vaults /// @return vaultSharePrice Price 1.0 vault share. Index of vault same as in previous array. /// @return vaultUserBalance User balance of vault. Index of vault same as in previous array. /// @return nft Ecosystem NFTs /// nft[0] BuildingPermitToken /// nft[1] VaultManager /// nft[2] StrategyLogic /// @return nftUserBalance User balance of NFT. Index of NFT same as in previous array. /// @return buildingPayPerVaultTokenBalance User balance of vault creation paying token function getBalance(address yourAccount) external view returns ( address[] memory token, uint[] memory tokenPrice, uint[] memory tokenUserBalance, address[] memory vault, uint[] memory vaultSharePrice, uint[] memory vaultUserBalance, address[] memory nft, uint[] memory nftUserBalance, uint buildingPayPerVaultTokenBalance ); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* WRITE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Add platform operator. /// Only governance and multisig can add operator. /// @param operator Address of new operator function addOperator(address operator) external; /// @notice Remove platform operator. /// Only governance and multisig can remove operator. /// @param operator Address of operator to remove function removeOperator(address operator) external; /// @notice Announce upgrade of platform proxies implementations /// Only governance and multisig can announce platform upgrades. /// @param newVersion New platform version. Version must be changed when upgrading. /// @param proxies Addresses of core contract proxies /// @param newImplementations New implementation for proxy. Index of proxy same as in previous array. function announcePlatformUpgrade( string memory newVersion, address[] memory proxies, address[] memory newImplementations ) external; /// @notice Upgrade platform /// Only operator (multisig is operator too) can ececute pending platform upgrade function upgrade() external; /// @notice Cancel pending platform upgrade /// Only operator (multisig is operator too) can ececute pending platform upgrade function cancelUpgrade() external; /// @notice Register AMM adapter in platform /// @param id AMM adapter ID string from AmmAdapterIdLib /// @param proxy Address of AMM adapter proxy function addAmmAdapter(string memory id, address proxy) external; // todo Only governance and multisig can set allowed bb-token vaults building limit /// @notice Set new vaults building limit for buy-back token /// @param bbToken Address of allowed buy-back token /// @param vaultsToBuild Number of vaults that can be built for BB-token function setAllowedBBTokenVaults(address bbToken, uint vaultsToBuild) external; // todo Only governance and multisig can add allowed boost reward token /// @notice Add new allowed boost reward token /// @param token Address of token function addAllowedBoostRewardToken(address token) external; // todo Only governance and multisig can remove allowed boost reward token /// @notice Remove allowed boost reward token /// @param token Address of allowed boost reward token function removeAllowedBoostRewardToken(address token) external; // todo Only governance and multisig can add default boost reward token /// @notice Add default boost reward token /// @param token Address of default boost reward token function addDefaultBoostRewardToken(address token) external; // todo Only governance and multisig can remove default boost reward token /// @notice Remove default boost reward token /// @param token Address of allowed boost reward token function removeDefaultBoostRewardToken(address token) external; // todo Only governance and multisig can add allowed boost reward token // todo Only governance and multisig can add default boost reward token /// @notice Add new allowed boost reward token /// @notice Add default boost reward token /// @param allowedBoostRewardToken Address of allowed boost reward token /// @param defaultBoostRewardToken Address of default boost reward token function addBoostTokens( address[] memory allowedBoostRewardToken, address[] memory defaultBoostRewardToken ) external; /// @notice Decrease allowed BB-token vault building limit when vault is built /// Only Factory can do it. /// @param bbToken Address of allowed buy-back token function useAllowedBBTokenVault(address bbToken) external; /// @notice Allow DeX aggregator routers to be used in the platform /// @param dexAggRouter Addresses of DeX aggreagator routers function addDexAggregators(address[] memory dexAggRouter) external; /// @notice Remove allowed DeX aggregator router from the platform /// @param dexAggRouter Address of DeX aggreagator router function removeDexAggregator(address dexAggRouter) external; /// @notice Change initial boost rewards settings /// @param minInitialBoostPerDay_ Minimal initial boost rewards per day USD amount which needs to create rewarding vault /// @param minInitialBoostDuration_ Minimal boost rewards vesting duration for initial boost function setInitialBoost(uint minInitialBoostPerDay_, uint minInitialBoostDuration_) external; /// @notice Update new minimum TVL for compensate. /// @param value New minimum TVL for compensate. function setMinTvlForFreeHardWork(uint value) external; /// @notice Set custom platform fee for vault /// @param vault Vault address /// @param platformFee Custom platform fee function setCustomVaultFee(address vault, uint platformFee) external; /// @notice Setup Rebalancer. /// Only Goverannce or Multisig can do this when Rebalancer is not set. /// @param rebalancer_ Proxy address of Bridge function setupRebalancer(address rebalancer_) external; /// @notice Setup Bridge. /// Only Goverannce or Multisig can do this when Bridge is not set. /// @param bridge_ Proxy address of Bridge function setupBridge(address bridge_) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; library VaultTypeLib { string internal constant COMPOUNDING = "Compounding"; string internal constant REWARDING = "Rewarding"; string internal constant REWARDING_MANAGED = "Rewarding Managed"; string internal constant SPLITTER_MANAGED = "Splitter Managed"; string internal constant SPLITTER_AUTO = "Splitter Automatic"; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./ConstantsLib.sol"; library CommonLib { function filterAddresses( address[] memory addresses, address addressToRemove ) external pure returns (address[] memory filteredAddresses) { uint len = addresses.length; uint newLen; // nosemgrep for (uint i; i < len; ++i) { if (addresses[i] != addressToRemove) { ++newLen; } } filteredAddresses = new address[](newLen); uint k; // nosemgrep for (uint i; i < len; ++i) { if (addresses[i] != addressToRemove) { filteredAddresses[k] = addresses[i]; ++k; } } } function formatUsdAmount(uint amount) external pure returns (string memory formattedPrice) { uint dollars = amount / 10 ** 18; string memory priceStr; if (dollars >= 1000) { uint kDollars = dollars / 1000; uint kDollarsFraction = (dollars - kDollars * 1000) / 10; string memory delimiter = "."; if (kDollarsFraction < 10) { delimiter = ".0"; } priceStr = string.concat(Strings.toString(kDollars), delimiter, Strings.toString(kDollarsFraction), "k"); } else if (dollars >= 100) { priceStr = Strings.toString(dollars); } else { uint dollarsFraction = (amount - dollars * 10 ** 18) / 10 ** 14; if (dollarsFraction > 0) { string memory dollarsFractionDelimiter = "."; if (dollarsFraction < 10) { dollarsFractionDelimiter = ".000"; } else if (dollarsFraction < 100) { dollarsFractionDelimiter = ".00"; } else if (dollarsFraction < 1000) { dollarsFractionDelimiter = ".0"; } priceStr = string.concat( Strings.toString(dollars), dollarsFractionDelimiter, Strings.toString(dollarsFraction) ); } else { priceStr = Strings.toString(dollars); } } formattedPrice = string.concat("$", priceStr); } function formatApr(uint apr) external pure returns (string memory formattedApr) { uint aprInt = apr * 100 / ConstantsLib.DENOMINATOR; uint aprFraction = (apr - aprInt * ConstantsLib.DENOMINATOR / 100) / 10; string memory delimiter = "."; if (aprFraction < 10) { delimiter = ".0"; } formattedApr = string.concat(Strings.toString(aprInt), delimiter, Strings.toString(aprFraction), "%"); } function implodeSymbols( address[] memory assets, string memory delimiter ) external view returns (string memory outString) { return implode(getSymbols(assets), delimiter); } function implode(string[] memory strings, string memory delimiter) public pure returns (string memory outString) { uint len = strings.length; if (len == 0) { return ""; } outString = strings[0]; // nosemgrep for (uint i = 1; i < len; ++i) { outString = string.concat(outString, delimiter, strings[i]); } return outString; } function getSymbols(address[] memory assets) public view returns (string[] memory symbols) { uint len = assets.length; symbols = new string[](len); // nosemgrep for (uint i; i < len; ++i) { symbols[i] = IERC20Metadata(assets[i]).symbol(); } } function bytesToBytes32(bytes memory b) external pure returns (bytes32 out) { // nosemgrep for (uint i; i < b.length; ++i) { out |= bytes32(b[i] & 0xFF) >> (i * 8); } // return out; } function bToHex(bytes memory buffer) external pure returns (string memory) { // Fixed buffer size for hexadecimal convertion bytes memory converted = new bytes(buffer.length * 2); bytes memory _base = "0123456789abcdef"; uint baseLength = _base.length; // nosemgrep for (uint i; i < buffer.length; ++i) { converted[i * 2] = _base[uint8(buffer[i]) / baseLength]; converted[i * 2 + 1] = _base[uint8(buffer[i]) % baseLength]; } return string(abi.encodePacked(converted)); } function shortId(string memory id) external pure returns (string memory) { uint words = 1; bytes memory idBytes = bytes(id); uint idBytesLength = idBytes.length; // nosemgrep for (uint i; i < idBytesLength; ++i) { if (keccak256(bytes(abi.encodePacked(idBytes[i]))) == keccak256(bytes(" "))) { ++words; } } bytes memory _shortId = new bytes(words); uint k = 1; _shortId[0] = idBytes[0]; // nosemgrep for (uint i = 1; i < idBytesLength; ++i) { if (keccak256(bytes(abi.encodePacked(idBytes[i]))) == keccak256(bytes(" "))) { if (keccak256(bytes(abi.encodePacked(idBytes[i + 1]))) == keccak256(bytes("0"))) { _shortId[k] = idBytes[i + 3]; } else { _shortId[k] = idBytes[i + 1]; } ++k; } } return string(abi.encodePacked(_shortId)); } function eq(string memory a, string memory b) external pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } function u2s(uint num) external pure returns (string memory) { return Strings.toString(num); } function i2s(int num) external pure returns (string memory) { return Strings.toString(num > 0 ? uint(num) : uint(-num)); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.21; library AmmAdapterIdLib { string public constant UNISWAPV3 = "UniswapV3"; string public constant ALGEBRA = "Algebra"; string public constant KYBER = "KyberSwap"; string public constant CURVE = "Curve"; string public constant SOLIDLY = "Solidly"; string public constant BALANCER_COMPOSABLE_STABLE = "BalancerComposableStable"; string public constant BALANCER_WEIGHTED = "BalancerWeighted"; string public constant ALGEBRA_V4 = "AlgebraV4"; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; interface IICHIVaultV4 { function ichiVaultFactory() external view returns (address); function pool() external view returns (address); function token0() external view returns (address); function allowToken0() external view returns (bool); function token1() external view returns (address); function allowToken1() external view returns (bool); function fee() external view returns (uint24); function tickSpacing() external view returns (int24); function affiliate() external view returns (address); function baseLower() external view returns (int24); function baseUpper() external view returns (int24); function limitLower() external view returns (int24); function limitUpper() external view returns (int24); function deposit0Max() external view returns (uint); function deposit1Max() external view returns (uint); function maxTotalSupply() external view returns (uint); function totalSupply() external view returns (uint); function hysteresis() external view returns (uint); function currentTick() external view returns (int24); function getTotalAmounts() external view returns (uint, uint); function deposit(uint, uint, address) external returns (uint); function withdraw(uint, address) external returns (uint, uint); function collectFees() external returns (uint fees0, uint fees1); function twapPeriod() external view returns (uint32); function auxTwapPeriod() external view returns (uint32); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.23; /// @dev https://sonicscan.org/address/0x413610103721df45c7e8333d5e34bb39975762f3#code interface IGaugeV2_CL { /// @notice deposit all TOKEN of msg.sender function depositAll() external; /// @notice deposit amount TOKEN function deposit(uint amount) external; /// @notice withdraw all token function withdrawAll() external; /// @notice withdraw a certain amount of TOKEN function withdraw(uint amount) external; /// @notice User harvest function called from distribution (voter allows harvest on multiple gauges) function getReward(address _user) external; /// @notice User harvest function function getReward() external; /// @dev Receive rewards from distribution function notifyRewardAmount(address token, uint reward) external; /// @notice get total reward for the duration function rewardForDuration() external view returns (uint); /// @notice see earned rewards for user function earned(address account) external view returns (uint); /// @notice reward for a single token function rewardPerToken() external view returns (uint); /// @notice last time reward function lastTimeRewardApplicable() external view returns (uint); /// @notice balance of a user function balanceOf(address account) external view returns (uint); /// @notice total supply held function totalSupply() external view returns (uint); /// @notice ALM address function TOKEN() external view returns (address); /// @notice Distro address (voter) function DISTRIBUTION() external view returns (address); /// @notice Reward token function rewardToken() external view returns (address); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.23; import "./pool/IAlgebraPoolImmutables.sol"; import "./pool/IAlgebraPoolState.sol"; import "./pool/IAlgebraPoolActions.sol"; import "./pool/IAlgebraPoolPermissionedActions.sol"; import "./pool/IAlgebraPoolEvents.sol"; import "./pool/IAlgebraPoolErrors.sol"; /// @title The interface for a Algebra Pool /// @dev The pool interface is broken up into many smaller pieces. /// This interface includes custom error definitions and cannot be used in older versions of Solidity. /// For older versions of Solidity use #IAlgebraPoolLegacy /// Credit to Uniswap Labs under GPL-2.0-or-later license: /// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces interface IAlgebraPool is IAlgebraPoolImmutables, IAlgebraPoolState, IAlgebraPoolActions, IAlgebraPoolPermissionedActions, IAlgebraPoolEvents, IAlgebraPoolErrors { // used only for combining interfaces }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.23; interface IVoterV3 { /// @notice claim LP gauge rewards function claimRewards(address[] memory _gauges) external; /// @notice notify reward amount for gauge /// @dev the function is called by the minter each epoch. Anyway anyone can top up some extra rewards. /// @param amount amount to distribute function notifyRewardAmount(uint amount) external; /// @notice distribute reward onyl for given gauges /// @dev this function is used in case some distribution fails function distribute(address[] memory _gauges) external; function minter() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. * * CAUTION: See Security Considerations above. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol) pragma solidity ^0.8.20; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev The ETH balance of the account is not enough to perform the operation. */ error AddressInsufficientBalance(address account); /** * @dev There's no code at `target` (it is not a contract). */ error AddressEmptyCode(address target); /** * @dev A call to an address target failed. The target may have reverted. */ error FailedInnerCall(); /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) { revert AddressInsufficientBalance(address(this)); } (bool success, ) = recipient.call{value: amount}(""); if (!success) { revert FailedInnerCall(); } } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason or custom error, it is bubbled * up by this function (like regular Solidity function calls). However, if * the call reverted with no returned reason, this function reverts with a * {FailedInnerCall} error. * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { if (address(this).balance < value) { revert AddressInsufficientBalance(address(this)); } (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an * unsuccessful call. */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata ) internal view returns (bytes memory) { if (!success) { _revert(returndata); } else { // only check if target is a contract if the call was successful and the return data is empty // otherwise we already know that it was a contract if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); } return returndata; } } /** * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the * revert reason or with a default {FailedInnerCall} error. */ function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) { if (!success) { _revert(returndata); } else { return returndata; } } /** * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}. */ function _revert(bytes memory returndata) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert FailedInnerCall(); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "../libs/SlotsLib.sol"; import "../../interfaces/IControllable.sol"; import "../../interfaces/IPlatform.sol"; /// @dev Base core contract. /// It store an immutable platform proxy address in the storage and provides access control to inherited contracts. /// @author Alien Deployer (https://github.com/a17) /// @author 0xhokugava (https://github.com/0xhokugava) abstract contract Controllable is Initializable, IControllable, ERC165 { using SlotsLib for bytes32; string public constant CONTROLLABLE_VERSION = "1.0.0"; bytes32 internal constant _PLATFORM_SLOT = bytes32(uint(keccak256("eip1967.controllable.platform")) - 1); bytes32 internal constant _CREATED_BLOCK_SLOT = bytes32(uint(keccak256("eip1967.controllable.created_block")) - 1); /// @dev Prevent implementation init constructor() { _disableInitializers(); } /// @notice Initialize contract after setup it as proxy implementation /// Save block.timestamp in the "created" variable /// @dev Use it only once after first logic setup /// @param platform_ Platform address //slither-disable-next-line naming-convention function __Controllable_init(address platform_) internal onlyInitializing { if (platform_ == address(0) || IPlatform(platform_).multisig() == address(0)) { revert IncorrectZeroArgument(); } SlotsLib.set(_PLATFORM_SLOT, platform_); // syntax for forge coverage _CREATED_BLOCK_SLOT.set(block.number); emit ContractInitialized(platform_, block.timestamp, block.number); } modifier onlyGovernance() { _requireGovernance(); _; } modifier onlyMultisig() { _requireMultisig(); _; } modifier onlyGovernanceOrMultisig() { _requireGovernanceOrMultisig(); _; } modifier onlyOperator() { _requireOperator(); _; } modifier onlyFactory() { _requireFactory(); _; } // ************* SETTERS/GETTERS ******************* /// @inheritdoc IControllable function platform() public view override returns (address) { return _PLATFORM_SLOT.getAddress(); } /// @inheritdoc IControllable function createdBlock() external view override returns (uint) { return _CREATED_BLOCK_SLOT.getUint(); } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IControllable).interfaceId || super.supportsInterface(interfaceId); } function _requireGovernance() internal view { if (IPlatform(platform()).governance() != msg.sender) { revert NotGovernance(); } } function _requireMultisig() internal view { if (!IPlatform(platform()).isOperator(msg.sender)) { revert NotMultisig(); } } function _requireGovernanceOrMultisig() internal view { IPlatform _platform = IPlatform(platform()); // nosemgrep if (_platform.governance() != msg.sender && _platform.multisig() != msg.sender) { revert NotGovernanceAndNotMultisig(); } } function _requireOperator() internal view { if (!IPlatform(platform()).isOperator(msg.sender)) { revert NotOperator(); } } function _requireFactory() internal view { if (IPlatform(platform()).factory() != msg.sender) { revert NotFactory(); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "./IStrategy.sol"; /// @notice Vault core interface. /// Derived implementations can be effective for building tokenized vaults with single or multiple underlying liquidity mining position. /// Fungible, static non-fungible and actively re-balancing liquidity is supported, as well as single token liquidity provided to lending protocols. /// Vaults can be used for active concentrated liquidity management and market making. /// @author Jude (https://github.com/iammrjude) /// @author JodsMigel (https://github.com/JodsMigel) interface IVault is IERC165 { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error NotEnoughBalanceToPay(); error FuseTrigger(); error ExceedSlippage(uint mintToUser, uint minToMint); error ExceedSlippageExactAsset(address asset, uint mintToUser, uint minToMint); error ExceedMaxSupply(uint maxSupply); error NotEnoughAmountToInitSupply(uint mintAmount, uint initialShares); error WaitAFewBlocks(); error StrategyZeroDeposit(); error NotSupported(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ event DepositAssets(address indexed account, address[] assets, uint[] amounts, uint mintAmount); event WithdrawAssets( address indexed sender, address indexed owner, address[] assets, uint sharesAmount, uint[] amountsOut ); event HardWorkGas(uint gasUsed, uint gasCost, bool compensated); event DoHardWorkOnDepositChanged(bool oldValue, bool newValue); event MaxSupply(uint maxShares); event VaultName(string newName); event VaultSymbol(string newSymbol); event MintFees( uint vaultManagerReceiverFee, uint strategyLogicReceiverFee, uint ecosystemRevenueReceiverFee, uint multisigReceiverFee ); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DATA TYPES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @custom:storage-location erc7201:stability.VaultBase struct VaultBaseStorage { /// @dev Prevents manipulations with deposit and withdraw in short time. /// For simplification we are setup new withdraw request on each deposit/transfer. mapping(address msgSender => uint blockNumber) withdrawRequests; /// @inheritdoc IVault IStrategy strategy; /// @inheritdoc IVault uint maxSupply; /// @inheritdoc IVault uint tokenId; /// @inheritdoc IVault bool doHardWorkOnDeposit; /// @dev Immutable vault type ID string _type; /// @dev Changed ERC20 name string changedName; /// @dev Changed ERC20 symbol string changedSymbol; } /// @title Vault Initialization Data /// @notice Data structure containing parameters for initializing a new vault. /// @dev This struct is commonly used as a parameter for the `initialize` function in vault contracts. /// @param platform Platform address providing access control, infrastructure addresses, fee settings, and upgrade capability. /// @param strategy Immutable strategy proxy used by the vault. /// @param name ERC20 name for the vault token. /// @param symbol ERC20 symbol for the vault token. /// @param tokenId NFT ID associated with the VaultManager. /// @param vaultInitAddresses Array of addresses used during vault initialization. /// @param vaultInitNums Array of uint values corresponding to initialization parameters. struct VaultInitializationData { address platform; address strategy; string name; string symbol; uint tokenId; address[] vaultInitAddresses; uint[] vaultInitNums; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Immutable vault type ID function vaultType() external view returns (string memory); /// @return uniqueInitAddresses Return required unique init addresses /// @return uniqueInitNums Return required unique init nums function getUniqueInitParamLength() external view returns (uint uniqueInitAddresses, uint uniqueInitNums); /// @notice Vault type extra data /// @return Vault type color, background color and other extra data function extra() external view returns (bytes32); /// @notice Immutable strategy proxy used by the vault /// @return Linked strategy function strategy() external view returns (IStrategy); /// @notice Max supply of shares in the vault. /// Since the starting share price is $1, this ceiling can be considered as an approximate TVL limit. /// @return Max total supply of vault function maxSupply() external view returns (uint); /// @dev VaultManager token ID. This tokenId earn feeVaultManager provided by Platform. function tokenId() external view returns (uint); /// @dev Trigger doHardwork on invest action. Enabled by default. function doHardWorkOnDeposit() external view returns (bool); /// @dev USD price of share with 18 decimals. /// ONLY FOR OFF-CHAIN USE. /// Not trusted vault share price can be manipulated. /// @return price_ Price of 1e18 shares with 18 decimals precision /// @return trusted True means oracle price, false means AMM spot price function price() external view returns (uint price_, bool trusted); /// @dev USD price of assets managed by strategy with 18 decimals /// ONLY FOR OFF-CHAIN USE. /// Not trusted TVL can be manipulated. /// @return tvl_ Total USD value of final assets in vault /// @return trusted True means TVL calculated based only on oracle prices, false means AMM spot price was used. function tvl() external view returns (uint tvl_, bool trusted); /// @dev Calculation of consumed amounts, shares amount and liquidity/underlying value for provided available amounts of strategy assets /// @param assets_ Assets suitable for vault strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic. /// @param amountsMax Available amounts of assets_ that user wants to invest in vault /// @return amountsConsumed Amounts of strategy assets that can be deposited by providing amountsMax /// @return sharesOut Amount of vault shares that will be minted /// @return valueOut Liquidity value or underlying token amount that will be received by the strategy function previewDepositAssets( address[] memory assets_, uint[] memory amountsMax ) external view returns (uint[] memory amountsConsumed, uint sharesOut, uint valueOut); /// @notice All available data on the latest declared APR (annual percentage rate) /// @return totalApr Total APR of investing money to vault. 18 decimals: 1e18 - +100% per year. /// @return strategyApr Strategy investmnt APR declared on last HardWork. /// @return assetsWithApr Assets with underlying APR /// @return assetsAprs Underlying APR of asset function getApr() external view returns (uint totalApr, uint strategyApr, address[] memory assetsWithApr, uint[] memory assetsAprs); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* WRITE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Write version of previewDepositAssets /// @param assets_ Assets suitable for vault strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic. /// @param amountsMax Available amounts of assets_ that user wants to invest in vault /// @return amountsConsumed Amounts of strategy assets that can be deposited by providing amountsMax /// @return sharesOut Amount of vault shares that will be minted /// @return valueOut Liquidity value or underlying token amount that will be received by the strategy function previewDepositAssetsWrite( address[] memory assets_, uint[] memory amountsMax ) external returns (uint[] memory amountsConsumed, uint sharesOut, uint valueOut); /// @dev Mint fee shares callback /// @param revenueAssets Assets returned by _claimRevenue function that was earned during HardWork /// @param revenueAmounts Assets amounts returned from _claimRevenue function that was earned during HardWork /// Only strategy can call this function hardWorkMintFeeCallback(address[] memory revenueAssets, uint[] memory revenueAmounts) external; /// @dev Deposit final assets (pool assets) to the strategy and minting of vault shares. /// If the strategy interacts with a pool or farms through an underlying token, then it will be minted. /// Emits a {DepositAssets} event with consumed amounts. /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic. /// @param amountsMax Available amounts of assets_ that user wants to invest in vault /// @param minSharesOut Slippage tolerance. Minimal shares amount which must be received by user. /// @param receiver Receiver of deposit. If receiver is zero address, receiver is msg.sender. function depositAssets( address[] memory assets_, uint[] memory amountsMax, uint minSharesOut, address receiver ) external; /// @dev Burning shares of vault and obtaining strategy assets. /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic. /// @param amountShares Shares amount for burning /// @param minAssetAmountsOut Slippage tolerance. Minimal amounts of strategy assets that user must receive. /// @return Amount of assets for withdraw. It's related to assets_ one-by-one. function withdrawAssets( address[] memory assets_, uint amountShares, uint[] memory minAssetAmountsOut ) external returns (uint[] memory); /// @dev Burning shares of vault and obtaining strategy assets. /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic. /// @param amountShares Shares amount for burning /// @param minAssetAmountsOut Slippage tolerance. Minimal amounts of strategy assets that user must receive. /// @param receiver Receiver of assets /// @param owner Owner of vault shares /// @return Amount of assets for withdraw. It's related to assets_ one-by-one. function withdrawAssets( address[] memory assets_, uint amountShares, uint[] memory minAssetAmountsOut, address receiver, address owner ) external returns (uint[] memory); /// @dev Setting of vault capacity /// @param maxShares If totalSupply() exceeds this value, deposits will not be possible function setMaxSupply(uint maxShares) external; /// @dev If activated will call doHardWork on strategy on some deposit actions /// @param value HardWork on deposit is enabled function setDoHardWorkOnDeposit(bool value) external; /// @notice Initialization function for the vault. /// @dev This function is usually called by the Factory during the creation of a new vault. /// @param vaultInitializationData Data structure containing parameters for vault initialization. function initialize(VaultInitializationData memory vaultInitializationData) external; /// @dev Calling the strategy HardWork by operator with optional compensation for spent gas from the vault balance function doHardWork() external; /// @dev Changing ERC20 name of vault function setName(string calldata newName) external; /// @dev Changing ERC20 symbol of vault function setSymbol(string calldata newSymbol) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../core/libs/CommonLib.sol"; import "../../core/libs/VaultTypeLib.sol"; import "../../core/libs/ConstantsLib.sol"; import "../../interfaces/ILPStrategy.sol"; import "../../interfaces/IPlatform.sol"; import "../../interfaces/IFactory.sol"; import "../../interfaces/ISwapper.sol"; import "../../interfaces/IRVault.sol"; library LPStrategyLib { using SafeERC20 for IERC20; uint internal constant SWAP_ASSETS_PRICE_IMPACT_TOLERANCE = 4_000; struct ProcessRevenueVars { string vaultYpe; uint compoundRatio; address bbToken; uint bbAmountBefore; } struct SwapForDepositProportionVars { ISwapper swapper; uint price; uint balance0; uint balance1; uint asset1decimals; uint threshold0; uint threshold1; } function LPStrategyBase_init( ILPStrategy.LPStrategyBaseStorage storage $, address platform, ILPStrategy.LPStrategyBaseInitParams memory params, string memory ammAdapterId ) external returns (address[] memory _assets, uint exchangeAssetIndex) { IPlatform.AmmAdapter memory ammAdapterData = IPlatform(platform).ammAdapter(keccak256(bytes(ammAdapterId))); if (ammAdapterData.proxy == address(0)) { revert ILPStrategy.ZeroAmmAdapter(); } IAmmAdapter ammAdapter = IAmmAdapter(ammAdapterData.proxy); _assets = ammAdapter.poolTokens(params.pool); uint len = _assets.length; exchangeAssetIndex = IFactory(IPlatform(platform).factory()).getExchangeAssetIndex(_assets); address swapper = IPlatform(params.platform).swapper(); // nosemgrep for (uint i; i < len; ++i) { IERC20(_assets[i]).forceApprove(swapper, type(uint).max); } $._feesOnBalance = new uint[](_assets.length); $.pool = params.pool; $.ammAdapter = ammAdapter; } function checkPreviewDepositAssets( address[] memory assets_, address[] memory _assets, uint[] memory amountsMax ) external pure { if (_assets.length != amountsMax.length) { revert ILPStrategy.IncorrectAmountsLength(); } checkAssets(assets_, _assets); } function checkAssets(address[] memory assets_, address[] memory _assets) public pure { uint len = assets_.length; if (len != _assets.length) { revert ILPStrategy.IncorrectAssetsLength(); } // nosemgrep for (uint i; i < len; ++i) { if (assets_[i] != _assets[i]) { revert ILPStrategy.IncorrectAssets(); } } } /// @dev For now this support only pools of 2 tokens function processRevenue( address platform, address vault, IAmmAdapter ammAdapter, uint exchangeAssetIndex, address pool, address[] memory assets_, uint[] memory amountsRemaining ) external returns (bool needCompound) { needCompound = true; ProcessRevenueVars memory vars; vars.vaultYpe = IVault(vault).vaultType(); if ( CommonLib.eq(vars.vaultYpe, VaultTypeLib.REWARDING) || CommonLib.eq(vars.vaultYpe, VaultTypeLib.REWARDING_MANAGED) ) { IRVault rVault = IRVault(vault); vars.compoundRatio = rVault.compoundRatio(); vars.bbToken = rVault.bbToken(); vars.bbAmountBefore = _balance(vars.bbToken); { uint otherAssetIndex = exchangeAssetIndex == 0 ? 1 : 0; uint exchangeAssetBBAmount = (ConstantsLib.DENOMINATOR - vars.compoundRatio) * amountsRemaining[exchangeAssetIndex] / ConstantsLib.DENOMINATOR; uint otherAssetBBAmount = (ConstantsLib.DENOMINATOR - vars.compoundRatio) * amountsRemaining[otherAssetIndex] / ConstantsLib.DENOMINATOR; // try to make less swaps if (otherAssetBBAmount > 0) { if (exchangeAssetBBAmount > 0) { uint otherAssetBBAmountPrice = ammAdapter.getPrice(pool, assets_[otherAssetIndex], address(0), otherAssetBBAmount); uint exchangeAssetAmountRemaining = amountsRemaining[exchangeAssetIndex] - exchangeAssetBBAmount; if (otherAssetBBAmountPrice <= exchangeAssetAmountRemaining) { otherAssetBBAmount = 0; exchangeAssetBBAmount += otherAssetBBAmountPrice; } } } ISwapper swapper = ISwapper(IPlatform(platform).swapper()); if (exchangeAssetBBAmount > 0) { if (assets_[exchangeAssetIndex] != vars.bbToken) { if (exchangeAssetBBAmount > swapper.threshold(assets_[exchangeAssetIndex])) { swapper.swap( assets_[exchangeAssetIndex], vars.bbToken, exchangeAssetBBAmount, SWAP_ASSETS_PRICE_IMPACT_TOLERANCE ); } } else { vars.bbAmountBefore -= exchangeAssetBBAmount; } } if (otherAssetBBAmount > 0) { if (assets_[otherAssetIndex] != vars.bbToken) { if (otherAssetBBAmount > swapper.threshold(assets_[otherAssetIndex])) { swapper.swap( assets_[otherAssetIndex], vars.bbToken, otherAssetBBAmount, SWAP_ASSETS_PRICE_IMPACT_TOLERANCE ); } } else { vars.bbAmountBefore -= otherAssetBBAmount; } } } uint bbAmount = _balance(vars.bbToken) - vars.bbAmountBefore; if (bbAmount > 0) { _approveIfNeeded(vars.bbToken, bbAmount, vault); rVault.notifyTargetRewardAmount(0, bbAmount); } if (vars.compoundRatio == 0) { needCompound = false; } } } /// @dev For now this support only pools of 2 tokens function swapForDepositProportion( address platform, IAmmAdapter ammAdapter, address _pool, address[] memory assets, uint prop0Pool ) external returns (uint[] memory amountsToDeposit) { amountsToDeposit = new uint[](2); SwapForDepositProportionVars memory vars; vars.swapper = ISwapper(IPlatform(platform).swapper()); vars.asset1decimals = IERC20Metadata(assets[1]).decimals(); vars.price = ammAdapter.getPrice(_pool, assets[1], assets[0], 10 ** vars.asset1decimals); vars.balance0 = _balance(assets[0]); vars.balance1 = _balance(assets[1]); vars.threshold0 = vars.swapper.threshold(assets[0]); vars.threshold1 = vars.swapper.threshold(assets[1]); if (vars.balance0 > vars.threshold0 || vars.balance1 > vars.threshold1) { uint balance1PricedInAsset0 = vars.balance1 * vars.price / 10 ** vars.asset1decimals; // here is change LPStrategyBase 1.0.3 // removed such code: `if (!(vars.balance1 > 0 && balance1PricedInAsset0 == 0)) {` // because in setup where one of asset if reward asset this condition not work uint prop0Balances = vars.balance1 > 0 ? vars.balance0 * 1e18 / (balance1PricedInAsset0 + vars.balance0) : 1e18; if (prop0Balances > prop0Pool) { // extra assets[0] uint correctAsset0Balance = (vars.balance0 + balance1PricedInAsset0) * prop0Pool / 1e18; uint toSwapAsset0 = vars.balance0 - correctAsset0Balance; // this is correct too, but difficult to understand.. // uint correctAsset0Balance = vars.balance1 * 1e18 / (1e18 - prop0Pool) * prop0Pool / 1e18 // * vars.price / 10 ** vars.asset1decimals; // uint extraBalance = vars.balance0 - correctAsset0Balance; // uint toSwapAsset0 = extraBalance - extraBalance * prop0Pool / 1e18; // swap assets[0] to assets[1] if (toSwapAsset0 > vars.threshold0) { vars.swapper.swap(assets[0], assets[1], toSwapAsset0, SWAP_ASSETS_PRICE_IMPACT_TOLERANCE); } } else if (prop0Pool > 0) { // extra assets[1] uint correctAsset1Balance = vars.balance0 * 1e18 / prop0Pool * (1e18 - prop0Pool) / 1e18 * 10 ** vars.asset1decimals / vars.price; uint extraBalance = vars.balance1 - correctAsset1Balance; uint toSwapAsset1 = extraBalance * prop0Pool / 1e18; // swap assets[1] to assets[0] if (toSwapAsset1 > vars.threshold1) { vars.swapper.swap(assets[1], assets[0], toSwapAsset1, SWAP_ASSETS_PRICE_IMPACT_TOLERANCE); } } amountsToDeposit[0] = _balance(assets[0]); amountsToDeposit[1] = _balance(assets[1]); } } function _balance(address token) internal view returns (uint) { return IERC20(token).balanceOf(address(this)); } /// @notice Make infinite approve of {token} to {spender} if the approved amount is less than {amount} /// @dev Should NOT be used for third-party pools function _approveIfNeeded(address token, uint amount, address spender) internal { if (IERC20(token).allowance(address(this), spender) < amount) { // infinite approve, 2*255 is more gas efficient then type(uint).max IERC20(token).forceApprove(spender, 2 ** 255); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; /// @notice On-chain price quoter and swapper by predefined routes /// @author Alien Deployer (https://github.com/a17) /// @author Jude (https://github.com/iammrjude) /// @author JodsMigel (https://github.com/JodsMigel) /// @author 0xhokugava (https://github.com/0xhokugava) interface ISwapper { event Swap(address indexed tokenIn, address indexed tokenOut, uint amount); event PoolAdded(PoolData poolData, bool assetAdded); event PoolRemoved(address token); event BlueChipAdded(PoolData poolData); event ThresholdChanged(address[] tokenIn, uint[] thresholdAmount); event BlueChipPoolRemoved(address tokenIn, address tokenOut); //region ----- Custom Errors ----- error UnknownAMMAdapter(); error LessThenThreshold(uint minimumAmount); error NoRouteFound(); error NoRoutesForAssets(); //endregion -- Custom Errors ----- struct PoolData { address pool; address ammAdapter; address tokenIn; address tokenOut; } struct AddPoolData { address pool; string ammAdapterId; address tokenIn; address tokenOut; } /// @notice All assets in pools added to Swapper /// @return Addresses of assets function assets() external view returns (address[] memory); /// @notice All blue chip assets in blue chip pools added to Swapper /// @return Addresses of blue chip assets function bcAssets() external view returns (address[] memory); /// @notice All assets in Swapper /// @return Addresses of assets and blue chip assets function allAssets() external view returns (address[] memory); /// @notice Add pools with largest TVL /// @param pools Largest pools with AMM adapter addresses /// @param rewrite Rewrite pool for tokenIn function addPools(PoolData[] memory pools, bool rewrite) external; /// @notice Add pools with largest TVL /// @param pools Largest pools with AMM adapter ID string /// @param rewrite Rewrite pool for tokenIn function addPools(AddPoolData[] memory pools, bool rewrite) external; /// @notice Add largest pools with the most popular tokens on the current network /// @param pools_ PoolData array with pool, tokens and AMM adapter address /// @param rewrite Change exist pool records function addBlueChipsPools(PoolData[] memory pools_, bool rewrite) external; /// @notice Add largest pools with the most popular tokens on the current network /// @param pools_ AddPoolData array with pool, tokens and AMM adapter string ID /// @param rewrite Change exist pool records function addBlueChipsPools(AddPoolData[] memory pools_, bool rewrite) external; /// @notice Retrieves pool data for a specified token swap in Blue Chip Pools. /// @dev This function provides information about the pool associated with the specified input and output tokens. /// @param tokenIn The input token address. /// @param tokenOut The output token address. /// @return poolData The data structure containing information about the Blue Chip Pool. /// @custom:opcodes view function blueChipsPools(address tokenIn, address tokenOut) external view returns (PoolData memory poolData); /// @notice Set swap threshold for token /// @dev Prevents dust swap. /// @param tokenIn Swap input token /// @param thresholdAmount Minimum amount of token for executing swap function setThresholds(address[] memory tokenIn, uint[] memory thresholdAmount) external; /// @notice Swap threshold for token /// @param token Swap input token /// @return threshold_ Minimum amount of token for executing swap function threshold(address token) external view returns (uint threshold_); /// @notice Price of given tokenIn against tokenOut /// @param tokenIn Swap input token /// @param tokenOut Swap output token /// @param amount Amount of tokenIn. If provide zero then amount is 1.0. /// @return Amount of tokenOut with decimals of tokenOut function getPrice(address tokenIn, address tokenOut, uint amount) external view returns (uint); /// @notice Return price the first poolData.tokenIn against the last poolData.tokenOut in decimals of tokenOut. /// @param route Array of pool address, swapper address tokenIn, tokenOut /// @param amount Amount of tokenIn. If provide zero then amount is 1.0. function getPriceForRoute(PoolData[] memory route, uint amount) external view returns (uint); /// @notice Check possibility of swap tokenIn for tokenOut /// @param tokenIn Swap input token /// @param tokenOut Swap output token /// @return Swap route exists function isRouteExist(address tokenIn, address tokenOut) external view returns (bool); /// @notice Build route for swap. No reverts inside. /// @param tokenIn Swap input token /// @param tokenOut Swap output token /// @return route Array of pools for swap tokenIn to tokenOut. Zero length indicate an error. /// @return errorMessage Possible reason why the route was not found. Empty for success routes. function buildRoute( address tokenIn, address tokenOut ) external view returns (PoolData[] memory route, string memory errorMessage); /// @notice Sell tokenIn for tokenOut /// @dev Assume approve on this contract exist /// @param tokenIn Swap input token /// @param tokenOut Swap output token /// @param amount Amount of tokenIn for swap. /// @param priceImpactTolerance Price impact tolerance. Must include fees at least. Denominator is 100_000. function swap(address tokenIn, address tokenOut, uint amount, uint priceImpactTolerance) external; /// @notice Swap by predefined route /// @param route Array of pool address, swapper address tokenIn, tokenOut. /// TokenIn from first item will be swaped to tokenOut of last . /// @param amount Amount of first item tokenIn. /// @param priceImpactTolerance Price impact tolerance. Must include fees at least. Denominator is 100_000. function swapWithRoute(PoolData[] memory route, uint amount, uint priceImpactTolerance) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol"; import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. */ abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors { /// @custom:storage-location erc7201:openzeppelin.storage.ERC20 struct ERC20Storage { mapping(address account => uint256) _balances; mapping(address account => mapping(address spender => uint256)) _allowances; uint256 _totalSupply; string _name; string _symbol; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00; function _getERC20Storage() private pure returns (ERC20Storage storage $) { assembly { $.slot := ERC20StorageLocation } } /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { ERC20Storage storage $ = _getERC20Storage(); $._name = name_; $._symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows $._totalSupply += value; } else { uint256 fromBalance = $._balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. $._balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. $._totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. $._balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * ``` * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } $._allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; library ConstantsLib { uint internal constant DENOMINATOR = 100_000; address internal constant DEAD_ADDRESS = 0xdEad000000000000000000000000000000000000; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; /// @notice The vaults are assembled at the factory by users through UI. /// Deployment rights of a vault are tokenized in VaultManager NFT. /// The holders of these tokens receive a share of the vault revenue and can manage vault if possible. /// @dev Rewards transfers to token owner or revenue receiver address managed by token owner. /// @author Alien Deployer (https://github.com/a17) /// @author Jude (https://github.com/iammrjude) /// @author JodsMigel (https://github.com/JodsMigel) interface IVaultManager is IERC721Metadata { //region ----- Events ----- event ChangeVaultParams(uint tokenId, address[] addresses, uint[] nums); event SetRevenueReceiver(uint tokenId, address receiver); //endregion -- Events ----- struct VaultData { // vault uint tokenId; address vault; string vaultType; string name; string symbol; string[] assetsSymbols; string[] rewardAssetsSymbols; uint sharePrice; uint tvl; uint totalApr; bytes32 vaultExtra; // strategy uint strategyTokenId; string strategyId; string strategySpecific; uint strategyApr; bytes32 strategyExtra; } //region ----- View functions ----- /// @notice Vault address managed by token /// @param tokenId ID of NFT. Starts from 0 and increments on mints. /// @return vault Address of vault proxy function tokenVault(uint tokenId) external view returns (address vault); /// @notice Receiver of token owner's platform revenue share /// @param tokenId ID of NFT /// @return receiver Address of vault manager fees receiver function getRevenueReceiver(uint tokenId) external view returns (address receiver); /// @notice All vaults data. /// The output values are matched by index in the arrays. /// @param vaultAddress Vault addresses /// @param name Vault name /// @param symbol Vault symbol /// @param vaultType Vault type ID string /// @param strategyId Strategy logic ID string /// @param sharePrice Current vault share price in USD. 18 decimals /// @param tvl Current vault TVL in USD. 18 decimals /// @param totalApr Last total vault APR. Denominator is 100_00. /// @param strategyApr Last strategy APR. Denominator is 100_00. /// @param strategySpecific Strategy specific name function vaults() external view returns ( address[] memory vaultAddress, string[] memory name, string[] memory symbol, string[] memory vaultType, string[] memory strategyId, uint[] memory sharePrice, uint[] memory tvl, uint[] memory totalApr, uint[] memory strategyApr, string[] memory strategySpecific ); /// @notice All deployed vault addresses /// @return vaultAddress Addresses of vault proxy function vaultAddresses() external view returns (address[] memory vaultAddress); /// @notice Vault extended info getter /// @param vault Address of vault proxy /// @return strategy /// @return strategyAssets /// @return underlying /// @return assetsWithApr Assets with underlying APRs that can be provided by AprOracle /// @return assetsAprs APRs of assets with APR. Matched by index wuth previous param. /// @return lastHardWork Last HardWork time function vaultInfo(address vault) external view returns ( address strategy, address[] memory strategyAssets, address underlying, address[] memory assetsWithApr, uint[] memory assetsAprs, uint lastHardWork ); //endregion -- View functions ----- //region ----- Write functions ----- /// @notice Changing managed vault init parameters by Vault Manager (owner of VaultManager NFT) /// @param tokenId ID of VaultManager NFT /// @param addresses Vault init addresses. Must contain also not changeable init addresses /// @param nums Vault init numbers. Must contant also not changeable init numbers function changeVaultParams(uint tokenId, address[] memory addresses, uint[] memory nums) external; /// @notice Minting of new token on deploying vault by Factory /// Only Factory can call this. /// @param to User which creates vault /// @param vault Address of vault proxy /// @return tokenId Minted token ID function mint(address to, address vault) external returns (uint tokenId); /// @notice Owner of token can change revenue reciever of platform fee share /// @param tokenId Owned token ID /// @param receiver New revenue receiver address function setRevenueReceiver(uint tokenId, address receiver) external; //endregion -- Write functions ----- }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; /// @dev Interface of developed strategy logic NFT /// @author Alien Deployer (https://github.com/a17) /// @author Jude (https://github.com/iammrjude) /// @author JodsMigel (https://github.com/JodsMigel) interface IStrategyLogic is IERC721Metadata { //region ----- Events ----- event SetRevenueReceiver(uint tokenId, address receiver); //endregion -- Events ----- struct StrategyData { uint strategyTokenId; string strategyId; bytes32 strategyExtra; } /// @notice Minting of new developed strategy by the factory /// @dev Parameters from StrategyDeveloperLib, StrategyIdLib. /// Only factory can call it. /// @param to Strategy developer address /// @param strategyLogicId Strategy logic ID string /// @return tokenId Minted token ID function mint(address to, string memory strategyLogicId) external returns (uint tokenId); /// @notice Owner of token can change address for receiving strategy logic revenue share /// Only owner of token can call it. /// @param tokenId Owned token ID /// @param receiver Address for receiving revenue function setRevenueReceiver(uint tokenId, address receiver) external; /// @notice Token ID to strategy logic ID map /// @param tokenId Owned token ID /// @return strategyLogicId Strategy logic ID string function tokenStrategyLogic(uint tokenId) external view returns (string memory strategyLogicId); /// @notice Current revenue reciever for token /// @param tokenId Token ID /// @return receiver Address for receiving revenue function getRevenueReceiver(uint tokenId) external view returns (address receiver); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; /// @dev Combining oracle and DeX spot prices /// @author Alien Deployer (https://github.com/a17) /// @author Jude (https://github.com/iammrjude) /// @author JodsMigel (https://github.com/JodsMigel) interface IPriceReader { //region ----- Events ----- event AdapterAdded(address adapter); event AdapterRemoved(address adapter); //endregion -- Events ----- /// @notice Price of asset /// @dev Price of 1.0 amount of asset in USD /// @param asset Address of asset /// @return price USD price with 18 decimals /// @return trusted Price from oracle function getPrice(address asset) external view returns (uint price, bool trusted); /// @notice Get USD price of specified assets and amounts /// @param assets_ Addresses of assets /// @param amounts_ Amount of asset. Index of asset same as in previous parameter. /// @return total Total USD value with 18 decimals /// @return assetAmountPrice USD price of asset amount. Index of assetAmountPrice same as in assets_ parameters. /// @return assetPrice USD price of asset. Index of assetAmountPrice same as in assets_ parameters. /// @return trusted True if only oracle prices was used for calculation. function getAssetsPrice( address[] memory assets_, uint[] memory amounts_ ) external view returns (uint total, uint[] memory assetAmountPrice, uint[] memory assetPrice, bool trusted); /// @notice Add oracle adapter to PriceReader /// Only operator (multisig is operator too) can add adapter /// @param adapter_ Address of price oracle proxy function addAdapter(address adapter_) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; /// @title The interface for the Algebra volatility oracle /// @dev This contract stores timepoints and calculates statistical averages interface IVolatilityOracle { /// @notice Returns data belonging to a certain timepoint /// @param index The index of timepoint in the array /// @dev There is more convenient function to fetch a timepoint: getTimepoints(). Which requires not an index but seconds /// @return initialized Whether the timepoint has been initialized and the values are safe to use /// @return blockTimestamp The timestamp of the timepoint /// @return tickCumulative The tick multiplied by seconds elapsed for the life of the pool as of the timepoint timestamp /// @return volatilityCumulative Cumulative standard deviation for the life of the pool as of the timepoint timestamp /// @return tick The tick at blockTimestamp /// @return averageTick Time-weighted average tick /// @return windowStartIndex Index of closest timepoint >= WINDOW seconds ago function timepoints(uint index) external view returns ( bool initialized, uint32 blockTimestamp, int56 tickCumulative, uint88 volatilityCumulative, int24 tick, int24 averageTick, uint16 windowStartIndex ); /// @notice Returns the index of the last timepoint that was written. /// @return index of the last timepoint written function timepointIndex() external view returns (uint16); /// @notice Returns the timestamp of the last timepoint that was written. /// @return timestamp of the last timepoint function lastTimepointTimestamp() external view returns (uint32); /// @notice Returns information about whether oracle is initialized /// @return true if oracle is initialized, otherwise false function isInitialized() external view returns (bool); /// @dev Reverts if a timepoint at or before the desired timepoint timestamp does not exist. /// 0 may be passed as `secondsAgo' to return the current cumulative values. /// If called with a timestamp falling between two timepoints, returns the counterfactual accumulator values /// at exactly the timestamp between the two timepoints. /// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors /// @param secondsAgo The amount of time to look back, in seconds, at which point to return a timepoint /// @return tickCumulative The cumulative tick since the pool was first initialized, as of `secondsAgo` /// @return volatilityCumulative The cumulative volatility value since the pool was first initialized, as of `secondsAgo` function getSingleTimepoint(uint32 secondsAgo) external view returns (int56 tickCumulative, uint88 volatilityCumulative); /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos` /// @dev Reverts if `secondsAgos` > oldest timepoint /// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return a timepoint /// @return tickCumulatives The cumulative tick since the pool was first initialized, as of each `secondsAgo` /// @return volatilityCumulatives The cumulative volatility values since the pool was first initialized, as of each `secondsAgo` function getTimepoints(uint32[] memory secondsAgos) external view returns (int56[] memory tickCumulatives, uint88[] memory volatilityCumulatives); /// @notice Fills uninitialized timepoints with nonzero value /// @dev Can be used to reduce the gas cost of future swaps /// @param startIndex The start index, must be not initialized /// @param amount of slots to fill, startIndex + amount must be <= type(uint16).max function prepayTimepointsStorageSlots(uint16 startIndex, uint16 amount) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; library UniswapV3MathLib { uint8 internal constant RESOLUTION = 96; uint internal constant Q96 = 0x1000000000000000000000000; uint internal constant TWO_96 = 2 ** 96; uint160 internal constant MIN_SQRT_RATIO = 4295128739 + 1; uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342 - 1; int24 internal constant MIN_TICK = -887272; int24 internal constant MAX_TICK = -MIN_TICK; struct ComputeFeesEarnedCommonParams { int24 tick; int24 lowerTick; int24 upperTick; uint128 liquidity; } function calcPriceOut( address tokenIn, address token0, uint160 sqrtPriceX96, uint tokenInDecimals, uint tokenOutDecimals, uint amount ) external pure returns (uint) { uint divider = tokenOutDecimals < 18 ? _max(10 ** tokenOutDecimals / 10 ** tokenInDecimals, 1) : 1; uint priceDigits = _countDigits(uint(sqrtPriceX96)); uint purePrice; uint precision; if (tokenIn == token0) { precision = 10 ** ((priceDigits < 29 ? 29 - priceDigits : 0) + tokenInDecimals); uint part = uint(sqrtPriceX96) * precision / TWO_96; purePrice = part * part; } else { precision = 10 ** ((priceDigits > 29 ? priceDigits - 29 : 0) + tokenInDecimals); uint part = TWO_96 * precision / uint(sqrtPriceX96); purePrice = part * part; } uint price = purePrice / divider / precision / (precision > 1e18 ? (precision / 1e18) : 1); if (amount != 0) { return price * amount / (10 ** tokenInDecimals); } else { return price; } } /// @dev Working only for Uniswap V3 native fee calculations. Not usable for Kyber's auto compounding fees and other specific implementations. function computeFeesEarned( ComputeFeesEarnedCommonParams memory params, uint feeGrowthGlobal, uint feeGrowthOutsideLower, uint feeGrowthOutsideUpper, uint feeGrowthInsideLast ) external pure returns (uint fee) { unchecked { // calculate fee growth below uint feeGrowthBelow; if (params.tick >= params.lowerTick) { feeGrowthBelow = feeGrowthOutsideLower; } else { feeGrowthBelow = feeGrowthGlobal - feeGrowthOutsideLower; } // calculate fee growth above uint feeGrowthAbove; if (params.tick < params.upperTick) { feeGrowthAbove = feeGrowthOutsideUpper; } else { feeGrowthAbove = feeGrowthGlobal - feeGrowthOutsideUpper; } uint feeGrowthInside = feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove; fee = mulDiv(params.liquidity, feeGrowthInside - feeGrowthInsideLast, 0x100000000000000000000000000000000); } } function getTicksInSpacing( int24 tick, int24 tickSpacing ) internal pure returns (int24 lowerTick, int24 upperTick) { // nosemgrep if (tick < 0 && tick / tickSpacing * tickSpacing != tick) { lowerTick = (tick / tickSpacing - 1) * tickSpacing; } else { lowerTick = tick / tickSpacing * tickSpacing; } upperTick = lowerTick + tickSpacing; } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries function getLiquidityForAmounts( uint160 sqrtRatioX96, int24 lowerTick, int24 upperTick, uint amount0, uint amount1 ) internal pure returns (uint128 liquidity) { uint160 sqrtRatioAX96 = getSqrtRatioAtTick(lowerTick); uint160 sqrtRatioBX96 = getSqrtRatioAtTick(upperTick); if (sqrtRatioAX96 > sqrtRatioBX96) { (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); } if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = _getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = _getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = _getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = _getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries function getAmountsForLiquidity( uint160 sqrtRatioX96, int24 lowerTick, int24 upperTick, uint128 liquidity ) internal pure returns (uint amount0, uint amount1) { uint160 sqrtRatioAX96 = getSqrtRatioAtTick(lowerTick); uint160 sqrtRatioBX96 = getSqrtRatioAtTick(upperTick); if (sqrtRatioAX96 > sqrtRatioBX96) { (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); } if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = _getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = _getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = _getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = _getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function _getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) { (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); } uint intermediate = mulDiv(sqrtRatioAX96, sqrtRatioBX96, Q96); return _toUint128(mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function _getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) { (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); } return _toUint128(mulDiv(amount1, Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The liquidity being valued /// @return amount0 The amount0 function _getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) { (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); } return _mulDivRoundingUp( 1, _mulDivRoundingUp(uint(liquidity) << RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96), sqrtRatioAX96 ); } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The liquidity being valued /// @return amount1 The amount1 function _getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) { (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); } return _mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, Q96); } /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint 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(uint a, uint b, uint denominator) public pure returns (uint 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 uint prod0; // Least significant 256 bits of the product uint 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 uint 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. // EDIT for 0.8 compatibility: // see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint uint twos = denominator & (~denominator + 1); // 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 uint 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 uint or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function _mulDivRoundingUp(uint a, uint b, uint denominator) internal pure returns (uint result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint).max); // nosemgrep result++; } } function _countDigits(uint n) internal pure returns (uint) { if (n == 0) { return 0; } uint count = 0; while (n != 0) { n = n / 10; ++count; } return count; } function _max(uint a, uint b) internal pure returns (uint) { return a > b ? a : b; } function _toUint128(uint x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @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) public pure returns (uint160 sqrtPriceX96) { uint absTick = tick < 0 ? uint(-int(tick)) : uint(int(tick)); // EDIT: 0.8 compatibility // nosemgrep require(absTick <= uint(int(MAX_TICK)), "T"); uint 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(uint).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)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.23; /// @title Errors emitted by a pool /// @notice Contains custom errors emitted by the pool /// @dev Custom errors are separated from the common pool interface for compatibility with older versions of Solidity interface IAlgebraPoolErrors { // #### pool errors #### /// @notice Emitted by the reentrancy guard error locked(); /// @notice Emitted if arithmetic error occurred error arithmeticError(); /// @notice Emitted if an attempt is made to initialize the pool twice error alreadyInitialized(); /// @notice Emitted if an attempt is made to mint or swap in uninitialized pool error notInitialized(); /// @notice Emitted if 0 is passed as amountRequired to swap function error zeroAmountRequired(); /// @notice Emitted if invalid amount is passed as amountRequired to swap function error invalidAmountRequired(); /// @notice Emitted if plugin fee param greater than fee/override fee error incorrectPluginFee(); /// @notice Emitted if the pool received fewer tokens than it should have error insufficientInputAmount(); /// @notice Emitted if there was an attempt to mint zero liquidity error zeroLiquidityDesired(); /// @notice Emitted if actual amount of liquidity is zero (due to insufficient amount of tokens received) error zeroLiquidityActual(); /// @notice Emitted if the pool received fewer tokens0 after flash than it should have error flashInsufficientPaid0(); /// @notice Emitted if the pool received fewer tokens1 after flash than it should have error flashInsufficientPaid1(); /// @notice Emitted if limitSqrtPrice param is incorrect error invalidLimitSqrtPrice(); /// @notice Tick must be divisible by tickspacing error tickIsNotSpaced(); /// @notice Emitted if a method is called that is accessible only to the factory owner or dedicated role error notAllowed(); /// @notice Emitted if new tick spacing exceeds max allowed value error invalidNewTickSpacing(); /// @notice Emitted if new community fee exceeds max allowed value error invalidNewCommunityFee(); /// @notice Emitted if an attempt is made to manually change the fee value, but dynamic fee is enabled error dynamicFeeActive(); /// @notice Emitted if an attempt is made by plugin to change the fee value, but dynamic fee is disabled error dynamicFeeDisabled(); /// @notice Emitted if an attempt is made to change the plugin configuration, but the plugin is not connected error pluginIsNotConnected(); /// @notice Emitted if a plugin returns invalid selector after hook call /// @param expectedSelector The expected selector error invalidHookResponse(bytes4 expectedSelector); // #### LiquidityMath errors #### /// @notice Emitted if liquidity underflows error liquiditySub(); /// @notice Emitted if liquidity overflows error liquidityAdd(); // #### TickManagement errors #### /// @notice Emitted if the topTick param not greater then the bottomTick param error topTickLowerOrEqBottomTick(); /// @notice Emitted if the bottomTick param is lower than min allowed value error bottomTickLowerThanMIN(); /// @notice Emitted if the topTick param is greater than max allowed value error topTickAboveMAX(); /// @notice Emitted if the liquidity value associated with the tick exceeds MAX_LIQUIDITY_PER_TICK error liquidityOverflow(); /// @notice Emitted if an attempt is made to interact with an uninitialized tick error tickIsNotInitialized(); /// @notice Emitted if there is an attempt to insert a new tick into the list of ticks with incorrect indexes of the previous and next ticks error tickInvalidLinks(); // #### SafeTransfer errors #### /// @notice Emitted if token transfer failed internally error transferFailed(); // #### TickMath errors #### /// @notice Emitted if tick is greater than the maximum or less than the minimum allowed value error tickOutOfRange(); /// @notice Emitted if price is greater than the maximum or less than the minimum allowed value error priceOutOfRange(); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.20; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ```solidity * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position is the index of the value in the `values` array plus 1. // Position 0 is used to mean a value is not in the set. mapping(bytes32 value => uint256) _positions; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._positions[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We cache the value's position to prevent multiple reads from the same storage slot uint256 position = set._positions[value]; if (position != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 valueIndex = position - 1; uint256 lastIndex = set._values.length - 1; if (valueIndex != lastIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the lastValue to the index where the value to delete is set._values[valueIndex] = lastValue; // Update the tracked position of the lastValue (that was just moved) set._positions[lastValue] = position; } // Delete the slot where the moved value was stored set._values.pop(); // Delete the tracked position for the deleted slot delete set._positions[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._positions[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol) pragma solidity ^0.8.20; import {Math} from "./math/Math.sol"; import {SignedMath} from "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant HEX_DIGITS = "0123456789abcdef"; uint8 private constant ADDRESS_LENGTH = 20; /** * @dev The `value` string doesn't fit in the specified `length`. */ error StringsInsufficientHexLength(uint256 value, uint256 length); /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), HEX_DIGITS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toStringSigned(int256 value) internal pure returns (string memory) { return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { uint256 localValue = value; bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_DIGITS[localValue & 0xf]; localValue >>= 4; } if (localValue != 0) { revert StringsInsufficientHexLength(value, length); } return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal * representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.23; /// @title Pool state that never changes /// @dev Credit to Uniswap Labs under GPL-2.0-or-later license: /// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces interface IAlgebraPoolImmutables { /// @notice The Algebra factory contract, which must adhere to the IAlgebraFactory 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 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.8.23; /// @title Pool state that can change /// @dev Important security note: when using this data by external contracts, it is necessary to take into account the possibility /// of manipulation (including read-only reentrancy). /// This interface is based on the UniswapV3 interface, credit to Uniswap Labs under GPL-2.0-or-later license: /// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces interface IAlgebraPoolState { /// @notice Safely get most important state values of Algebra Integral AMM /// @dev Several values exposed as a single method to save gas when accessed externally. /// **Important security note: this method checks reentrancy lock and should be preferred in most cases**. /// @return sqrtPrice The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value /// @return tick The current global tick of the pool. May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary /// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin /// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic /// @return activeLiquidity The currently in-range liquidity available to the pool /// @return nextTick The next initialized tick after current global tick /// @return previousTick The previous initialized tick before (or at) current global tick function safelyGetStateOfAMM() external view returns ( uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick ); /// @notice Allows to easily get current reentrancy lock status /// @dev can be used to prevent read-only reentrancy. /// This method just returns `globalState.unlocked` value /// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false function isUnlocked() external view returns (bool unlocked); // ! IMPORTANT security note: the pool state can be manipulated. // ! The following methods do not check reentrancy lock themselves. /// @notice The globalState structure in the pool stores many values but requires only one slot /// and is exposed as a single method to save gas when accessed externally. /// @dev **important security note: caller should check `unlocked` flag to prevent read-only reentrancy** /// @return price The current price of the pool as a sqrt(dToken1/dToken0) 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(price) if the price is on a tick boundary /// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin /// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic /// @return communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%) /// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked); /// @notice Look up information about a specific tick in the pool /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy** /// @param tick The tick to look up /// @return liquidityTotal The total amount of position liquidity that uses the pool either as tick lower or tick upper /// @return liquidityDelta How much liquidity changes when the pool price crosses the tick /// @return prevTick The previous tick in tick list /// @return nextTick The next tick in tick list /// @return outerFeeGrowth0Token The fee growth on the other side of the tick from the current tick in token0 /// @return outerFeeGrowth1Token The fee growth on the other side of the tick from the current tick in token1 /// 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 ( uint liquidityTotal, int128 liquidityDelta, int24 prevTick, int24 nextTick, uint outerFeeGrowth0Token, uint outerFeeGrowth1Token ); /// @notice The timestamp of the last sending of tokens to vault/plugin /// @return The timestamp truncated to 32 bits function lastFeeTransferTimestamp() external view returns (uint32); /// @notice The amounts of token0 and token1 that will be sent to the vault /// @dev Will be sent FEE_TRANSFER_FREQUENCY after communityFeeLastTimestamp /// @return communityFeePending0 The amount of token0 that will be sent to the vault /// @return communityFeePending1 The amount of token1 that will be sent to the vault function getCommunityFeePending() external view returns (uint128 communityFeePending0, uint128 communityFeePending1); /// @notice The amounts of token0 and token1 that will be sent to the plugin /// @dev Will be sent FEE_TRANSFER_FREQUENCY after feeLastTransferTimestamp /// @return pluginFeePending0 The amount of token0 that will be sent to the plugin /// @return pluginFeePending1 The amount of token1 that will be sent to the plugin function getPluginFeePending() external view returns (uint128 pluginFeePending0, uint128 pluginFeePending1); /// @notice Returns the address of currently used plugin /// @dev The plugin is subject to change /// @return pluginAddress The address of currently used plugin function plugin() external view returns (address pluginAddress); /// @notice The contract to which community fees are transferred /// @return communityVaultAddress The communityVault address function communityVault() external view returns (address communityVaultAddress); /// @notice Returns 256 packed tick initialized boolean values. See TickTree for more information /// @param wordPosition Index of 256-bits word with ticks /// @return The 256-bits word with packed ticks info function tickTable(int16 wordPosition) external view returns (uint); /// @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 /// @return The fee growth accumulator for token0 function totalFeeGrowth0Token() external view returns (uint); /// @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 /// @return The fee growth accumulator for token1 function totalFeeGrowth1Token() external view returns (uint); /// @notice The current pool fee value /// @dev In case dynamic fee is enabled in the pool, this method will call the plugin to get the current fee. /// If the plugin implements complex fee logic, this method may return an incorrect value or revert. /// In this case, see the plugin implementation and related documentation. /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy** /// @return currentFee The current pool fee value in hundredths of a bip, i.e. 1e-6 function fee() external view returns (uint16 currentFee); /// @notice The tracked token0 and token1 reserves of pool /// @dev If at any time the real balance is larger, the excess will be transferred to liquidity providers as additional fee. /// If the balance exceeds uint128, the excess will be sent to the communityVault. /// @return reserve0 The last known reserve of token0 /// @return reserve1 The last known reserve of token1 function getReserves() external view returns (uint128 reserve0, uint128 reserve1); /// @notice Returns the information about a position by the position's key /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy** /// @param key The position's key is a packed concatenation of the owner address, bottomTick and topTick indexes /// @return liquidity The amount of liquidity in the position /// @return innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke /// @return innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke /// @return fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke /// @return fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns (uint liquidity, uint innerFeeGrowth0Token, uint innerFeeGrowth1Token, uint128 fees0, uint128 fees1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks. /// Returned value cannot exceed type(uint128).max /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy** /// @return The current in range liquidity function liquidity() external view returns (uint128); /// @notice The current tick spacing /// @dev Ticks can only be initialized by new mints at multiples of this value /// e.g.: a tickSpacing of 60 means ticks can be initialized every 60th tick, i.e., ..., -120, -60, 0, 60, 120, ... /// However, tickspacing can be changed after the ticks have been initialized. /// This value is an int24 to avoid casting even though it is always positive. /// @return The current tick spacing function tickSpacing() external view returns (int24); /// @notice The previous initialized tick before (or at) current global tick /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy** /// @return The previous initialized tick function prevTickGlobal() external view returns (int24); /// @notice The next initialized tick after current global tick /// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy** /// @return The next initialized tick function nextTickGlobal() external view returns (int24); /// @notice The root of tick search tree /// @dev Each bit corresponds to one node in the second layer of tick tree: '1' if node has at least one active bit. /// **important security note: caller should check reentrancy lock to prevent read-only reentrancy** /// @return The root of tick search tree as bitmap function tickTreeRoot() external view returns (uint32); /// @notice The second layer of tick search tree /// @dev Each bit in node corresponds to one node in the leafs layer (`tickTable`) of tick tree: '1' if leaf has at least one active bit. /// **important security note: caller should check reentrancy lock to prevent read-only reentrancy** /// @return The node of tick search tree second layer function tickTreeSecondLayer(int16) external view returns (uint); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.23; /// @title Permissionless pool actions /// @dev Credit to Uniswap Labs under GPL-2.0-or-later license: /// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces interface IAlgebraPoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @dev Initialization should be done in one transaction with pool creation to avoid front-running /// @param initialPrice The initial sqrt price of the pool as a Q64.96 function initialize(uint160 initialPrice) external; /// @notice Adds liquidity for the given recipient/bottomTick/topTick position /// @dev The caller of this method receives a callback in the form of IAlgebraMintCallback#algebraMintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on bottomTick, topTick, the amount of liquidity, and the current price. /// @param leftoversRecipient The address which will receive potential surplus of paid tokens /// @param recipient The address for which the liquidity will be created /// @param bottomTick The lower tick of the position in which to add liquidity /// @param topTick The upper tick of the position in which to add liquidity /// @param liquidityDesired The desired 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 /// @return liquidityActual The actual minted amount of liquidity function mint( address leftoversRecipient, address recipient, int24 bottomTick, int24 topTick, uint128 liquidityDesired, bytes calldata data ) external returns (uint amount0, uint amount1, uint128 liquidityActual); /// @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 bottomTick The lower tick of the position for which to collect fees /// @param topTick 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 bottomTick, int24 topTick, 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 bottomTick The lower tick of the position for which to burn liquidity /// @param topTick The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @param data Any data that should be passed through to the plugin /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 bottomTick, int24 topTick, uint128 amount, bytes calldata data ) external returns (uint amount0, uint amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param limitSqrtPrice 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. If using the Router it should contain SwapRouter#SwapCallbackData /// @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 zeroToOne, int amountRequired, uint160 limitSqrtPrice, bytes calldata data ) external returns (int amount0, int amount1); /// @notice Swap token0 for token1, or token1 for token0 with prepayment /// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback /// caller must send tokens in callback before swap calculation /// the actually sent amount of tokens is used for further calculations /// @param leftoversRecipient The address which will receive potential surplus of paid tokens /// @param recipient The address to receive the output of the swap /// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountToSell The amount of the swap, only positive (exact input) amount allowed /// @param limitSqrtPrice 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. If using the Router it should contain SwapRouter#SwapCallbackData /// @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 swapWithPaymentInAdvance( address leftoversRecipient, address recipient, bool zeroToOne, int amountToSell, uint160 limitSqrtPrice, bytes calldata data ) external returns (int amount0, int 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 IAlgebraFlashCallback#algebraFlashCallback /// @dev All excess tokens paid in the callback are distributed to currently in-range liquidity providers as an additional fee. /// If there are no in-range liquidity providers, the fee will be transferred to the first active provider in the future /// @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, uint amount0, uint amount1, bytes calldata data) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.23; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by permissioned addresses /// @dev Credit to Uniswap Labs under GPL-2.0-or-later license: /// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces interface IAlgebraPoolPermissionedActions { /// @notice Set the community's % share of the fees. Only factory owner or POOLS_ADMINISTRATOR_ROLE role /// @param newCommunityFee The new community fee percent in thousandths (1e-3) function setCommunityFee(uint16 newCommunityFee) external; /// @notice Set the new tick spacing values. Only factory owner or POOLS_ADMINISTRATOR_ROLE role /// @param newTickSpacing The new tick spacing value function setTickSpacing(int24 newTickSpacing) external; /// @notice Set the new plugin address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role /// @param newPluginAddress The new plugin address function setPlugin(address newPluginAddress) external; /// @notice Set new plugin config. Only factory owner or POOLS_ADMINISTRATOR_ROLE role /// @param newConfig In the new configuration of the plugin, /// each bit of which is responsible for a particular hook. function setPluginConfig(uint8 newConfig) external; /// @notice Set new community fee vault address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role /// @dev Community fee vault receives collected community fees. /// **accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address** /// @param newCommunityVault The address of new community fee vault function setCommunityVault(address newCommunityVault) external; /// @notice Set new pool fee. Can be called by owner if dynamic fee is disabled. /// Called by the plugin if dynamic fee is enabled /// @param newFee The new fee value function setFee(uint16 newFee) external; /// @notice Forces balances to match reserves. Excessive tokens will be distributed between active LPs /// @dev Only plugin can call this function function sync() external; /// @notice Forces balances to match reserves. Excessive tokens will be sent to msg.sender /// @dev Only plugin can call this function function skim() external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.23; /// @title Events emitted by a pool /// @dev Credit to Uniswap Labs under GPL-2.0-or-later license: /// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces interface IAlgebraPoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swaps cannot be emitted by the pool before Initialize /// @param price 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 price, 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 bottomTick The lower tick of the position /// @param topTick The upper tick of the position /// @param liquidityAmount 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 bottomTick, int24 indexed topTick, uint128 liquidityAmount, uint amount0, uint amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @param owner The owner of the position for which fees are collected /// @param recipient The address that received fees /// @param bottomTick The lower tick of the position /// @param topTick 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 bottomTick, int24 indexed topTick, 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 bottomTick The lower tick of the position /// @param topTick The upper tick of the position /// @param liquidityAmount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn /// @param pluginFee The fee to be sent to the plugin event Burn( address indexed owner, int24 indexed bottomTick, int24 indexed topTick, uint128 liquidityAmount, uint amount0, uint amount1, uint24 pluginFee ); /// @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 price 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 /// @param overrideFee The fee to be applied to the trade /// @param pluginFee The fee to be sent to the plugin event Swap( address indexed sender, address indexed recipient, int amount0, int amount1, uint160 price, uint128 liquidity, int24 tick, uint24 overrideFee, uint24 pluginFee ); /// @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, uint amount0, uint amount1, uint paid0, uint paid1); /// @notice Emitted when the pool has higher balances than expected. /// Any excess of tokens will be distributed between liquidity providers as fee. /// @dev Fees after flash also will trigger this event due to mechanics of flash. /// @param amount0 The excess of token0 /// @param amount1 The excess of token1 event ExcessTokens(uint amount0, uint amount1); /// @notice Emitted when the community fee is changed by the pool /// @param communityFeeNew The updated value of the community fee in thousandths (1e-3) event CommunityFee(uint16 communityFeeNew); /// @notice Emitted when the tick spacing changes /// @param newTickSpacing The updated value of the new tick spacing event TickSpacing(int24 newTickSpacing); /// @notice Emitted when the plugin address changes /// @param newPluginAddress New plugin address event Plugin(address newPluginAddress); /// @notice Emitted when the plugin config changes /// @param newPluginConfig New plugin config event PluginConfig(uint8 newPluginConfig); /// @notice Emitted when the fee changes inside the pool /// @param fee The current fee in hundredths of a bip, i.e. 1e-6 event Fee(uint16 fee); /// @notice Emitted when the community vault address changes /// @param newCommunityVault New community vault event CommunityVault(address newCommunityVault); /// @notice Emitted when the plugin does skim the excess of tokens /// @param to THe receiver of tokens (plugin) /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 event Skim(address indexed to, uint amount0, uint amount1); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.20; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Storage of the initializable contract. * * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions * when using with upgradeable contracts. * * @custom:storage-location erc7201:openzeppelin.storage.Initializable */ struct InitializableStorage { /** * @dev Indicates that the contract has been initialized. */ uint64 _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool _initializing; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00; /** * @dev The contract is already initialized. */ error InvalidInitialization(); /** * @dev The contract is not initializing. */ error NotInitializing(); /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint64 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in * production. * * Emits an {Initialized} event. */ modifier initializer() { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); // Cache values to avoid duplicated sloads bool isTopLevelCall = !$._initializing; uint64 initialized = $._initialized; // Allowed calls: // - initialSetup: the contract is not in the initializing state and no previous version was // initialized // - construction: the contract is initialized at version 1 (no reininitialization) and the // current contract is just being deployed bool initialSetup = initialized == 0 && isTopLevelCall; bool construction = initialized == 1 && address(this).code.length == 0; if (!initialSetup && !construction) { revert InvalidInitialization(); } $._initialized = 1; if (isTopLevelCall) { $._initializing = true; } _; if (isTopLevelCall) { $._initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint64 version) { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing || $._initialized >= version) { revert InvalidInitialization(); } $._initialized = version; $._initializing = true; _; $._initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { _checkInitializing(); _; } /** * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}. */ function _checkInitializing() internal view virtual { if (!_isInitializing()) { revert NotInitializing(); } } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing) { revert InvalidInitialization(); } if ($._initialized != type(uint64).max) { $._initialized = type(uint64).max; emit Initialized(type(uint64).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint64) { return _getInitializableStorage()._initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _getInitializableStorage()._initializing; } /** * @dev Returns a pointer to the storage namespace. */ // solhint-disable-next-line var-name-mixedcase function _getInitializableStorage() private pure returns (InitializableStorage storage $) { assembly { $.slot := INITIALIZABLE_STORAGE } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; /// @title Minimal library for setting / getting slot variables (used in upgradable proxy contracts) library SlotsLib { /// @dev Gets a slot as an address function getAddress(bytes32 slot) internal view returns (address result) { assembly { result := sload(slot) } } /// @dev Gets a slot as uint256 function getUint(bytes32 slot) internal view returns (uint result) { assembly { result := sload(slot) } } /// @dev Sets a slot with address /// @notice Check address for 0 at the setter function set(bytes32 slot, address value) internal { assembly { sstore(slot, value) } } /// @dev Sets a slot with uint function set(bytes32 slot, uint value) internal { assembly { sstore(slot, value) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.23; import "./IVault.sol"; /// @notice Interface of Rewarding Vault /// @author Alien Deployer (https://github.com/a17) /// @author JodsMigel (https://github.com/JodsMigel) /// @author 0xhokugava (https://github.com/0xhokugava) interface IRVault is IVault { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error NotAllowed(); error Overflow(uint maxAmount); error RTNotFound(); error NoBBToken(); error NotAllowedBBToken(); error IncorrectNums(); error ZeroToken(); error ZeroVestingDuration(); error TooHighCompoundRation(); error RewardIsTooSmall(); // error RewardIsTooBig(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ event RewardAdded(address rewardToken, uint reward); event RewardPaid(address indexed user, address rewardToken, uint reward); event SetRewardsRedirect(address owner, address receiver); event AddedRewardToken(address indexed token, uint indexed tokenIndex); event CompoundRatio(uint compoundRatio_); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DATA TYPES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @custom:storage-location erc7201:stability.RVaultBase struct RVaultBaseStorage { /// @inheritdoc IRVault mapping(uint tokenIndex => address rewardToken) rewardToken; /// @inheritdoc IRVault mapping(uint tokenIndex => uint durationSeconds) duration; /// @inheritdoc IRVault mapping(address owner => address receiver) rewardsRedirect; /// @dev Timestamp value when current period of rewards will be ended mapping(uint tokenIndex => uint finishTimestamp) periodFinishForToken; /// @dev Reward rate in normal circumstances is distributed rewards divided on duration mapping(uint tokenIndex => uint rewardRate) rewardRateForToken; /// @dev Last rewards snapshot time. Updated on each share movements mapping(uint tokenIndex => uint lastUpdateTimestamp) lastUpdateTimeForToken; /// @dev Rewards snapshot calculated from rewardPerToken(rt). Updated on each share movements mapping(uint tokenIndex => uint rewardPerTokenStored) rewardPerTokenStoredForToken; /// @dev User personal reward rate snapshot. Updated on each share movements mapping(uint tokenIndex => mapping(address user => uint rewardPerTokenPaid)) userRewardPerTokenPaidForToken; /// @dev User personal earned reward snapshot. Updated on each share movements mapping(uint tokenIndex => mapping(address user => uint earned)) rewardsForToken; /// @inheritdoc IRVault uint rewardTokensTotal; /// @inheritdoc IRVault uint compoundRatio; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VIEW FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice All vault rewarding tokens /// @return Reward token addresses function rewardTokens() external view returns (address[] memory); /// @return Total of bbToken + boost reward tokens function rewardTokensTotal() external view returns (uint); /// @notice Immutable reward buy-back token with tokenIndex 0 function bbToken() external view returns (address); /// @dev A mapping of reward tokens that able to be distributed to this contract. /// Token with index 0 always is bbToken. function rewardToken(uint tokenIndex) external view returns (address rewardToken_); /// @notice Re-investing ratio /// @dev Changeable ratio of revenue part for re-investing. Other part goes to rewarding by bbToken. /// @return Ratio of re-investing part of revenue. Denominator is 100_000. function compoundRatio() external view returns (uint); /// @notice Vesting period for distribution reward /// @param tokenIndex Index of rewarding token /// @return durationSeconds Duration for distributing of notified reward function duration(uint tokenIndex) external view returns (uint durationSeconds); /// @notice Return earned rewards for specific token and account /// Accurate value returns only after updateRewards call /// ((balanceOf(account) /// * (rewardPerToken - userRewardPerTokenPaidForToken)) / 10**18) + rewardsForToken function earned(uint rewardTokenIndex, address account) external view returns (uint); /// @notice Return reward per token ratio by reward token address /// rewardPerTokenStoredForToken + ( /// (lastTimeRewardApplicable - lastUpdateTimeForToken) /// * rewardRateForToken * 10**18 / totalSupply) /// @param rewardTokenIndex Index of reward token /// @return Return reward per token ratio by reward token address function rewardPerToken(uint rewardTokenIndex) external view returns (uint); /// @dev Receiver of rewards can be set by multisig when owner cant claim rewards himself /// @param owner Token owner address /// @return receiver Return reward's receiver function rewardsRedirect(address owner) external view returns (address receiver); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* WRITE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @notice Filling vault with rewards /// @dev Update rewardRateForToken /// If period ended: reward / duration /// else add leftover to the reward amount and refresh the period /// (reward + ((periodFinishForToken - block.timestamp) * rewardRateForToken)) / duration /// @param tokenIndex Index of rewarding token /// @param amount Amount for rewarding function notifyTargetRewardAmount(uint tokenIndex, uint amount) external; /// @notice Update and Claim all rewards for caller function getAllRewards() external; /// @notice Update and Claim rewards for specific token /// @param rt Index of reward token function getReward(uint rt) external; /// @dev All rewards for given owner could be claimed for receiver address. /// @param owner Token owner address /// @param receiver New reward's receiver function setRewardsRedirect(address owner, address receiver) external; /// @notice Update and Claim all rewards for given owner address. Send them to predefined receiver. /// @param owner Token owner address function getAllRewardsAndRedirect(address owner) external; /// @notice Update and Claim all rewards for the given owner. /// Sender should have allowance for push rewards for the owner. /// @param owner Token owner address function getAllRewardsFor(address owner) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol) pragma solidity ^0.8.20; /** * @dev Standard ERC20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.20; import {IERC721} from "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.20; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.20; import {IERC165} from "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon * a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or * {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon * a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721 * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must * understand this adds an external call which potentially creates a reentrancy vulnerability. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the address zero. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); }
{ "remappings": [ "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/", "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/", "@solady/=lib/solady/src/", "ds-test/=lib/forge-std/lib/ds-test/src/", "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/", "forge-std/=lib/forge-std/src/", "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/", "openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/", "solady/=lib/solady/", "openzeppelin-contracts/=lib/openzeppelin-contracts/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "shanghai", "viaIR": false, "libraries": { "src/core/libs/CommonLib.sol": { "CommonLib": "0x4f76ADd676c04ecA837130CeB58Bc173de8799dE" }, "src/strategies/libs/ISFLib.sol": { "ISFLib": "0xE3c14573ccD72F95a739f297DcFa8D525aA330aC" }, "src/strategies/libs/LPStrategyLib.sol": { "LPStrategyLib": "0xF732Df3f82d1Ce0234bF5EE6933Fd370b8B30f2a" }, "src/strategies/libs/StrategyLib.sol": { "StrategyLib": "0xe347A67358dD7cBa1EB146B9a60172a10cb8abEe" }, "src/strategies/libs/UniswapV3MathLib.sol": { "UniswapV3MathLib": "0xbbc63ee4a06bf1F2432ccC4d70103e3D465fcA39" } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"AlreadyExist","type":"error"},{"inputs":[],"name":"BadFarm","type":"error"},{"inputs":[],"name":"ETHTransferFailed","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"IncorrectAmountsLength","type":"error"},{"inputs":[],"name":"IncorrectArrayLength","type":"error"},{"inputs":[],"name":"IncorrectAssets","type":"error"},{"inputs":[],"name":"IncorrectAssetsLength","type":"error"},{"inputs":[],"name":"IncorrectInitParams","type":"error"},{"inputs":[],"name":"IncorrectMsgSender","type":"error"},{"inputs":[],"name":"IncorrectStrategyId","type":"error"},{"inputs":[],"name":"IncorrectZeroArgument","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotExist","type":"error"},{"inputs":[],"name":"NotFactory","type":"error"},{"inputs":[],"name":"NotGovernance","type":"error"},{"inputs":[],"name":"NotGovernanceAndNotMultisig","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NotMultisig","type":"error"},{"inputs":[],"name":"NotOperator","type":"error"},{"inputs":[],"name":"NotPlatform","type":"error"},{"inputs":[],"name":"NotReadyForHardWork","type":"error"},{"inputs":[],"name":"NotTheOwner","type":"error"},{"inputs":[],"name":"NotVault","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"ZeroAmmAdapter","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"platform","type":"address"},{"indexed":false,"internalType":"uint256","name":"ts","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"block","type":"uint256"}],"name":"ContractInitialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"vaultManagerReceiverFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"strategyLogicReceiverFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ecosystemRevenueReceiverFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"multisigReceiverFee","type":"uint256"}],"name":"ExtractFees","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256[]","name":"fees","type":"uint256[]"}],"name":"FeesClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"apr","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"compoundApr","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"earned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tvl","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"duration","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sharePrice","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"assetPrices","type":"uint256[]"}],"name":"HardWork","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"RewardsClaimed","type":"event"},{"inputs":[],"name":"CONTROLLABLE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION_FARMING_STRATEGY_BASE","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION_LP_STRATEGY_BASE","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION_STRATEGY_BASE","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ammAdapter","outputs":[{"internalType":"contract IAmmAdapter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ammAdapterId","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"assets","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"assetsAmounts","outputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256[]","name":"amounts_","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"autoCompoundingByUnderlyingProtocol","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"canFarm","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"createdBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"depositAssets","outputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositUnderlying","outputs":[{"internalType":"uint256[]","name":"amountsConsumed","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"description","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"doHardWork","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"emergencyStopInvesting","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"extra","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"farmId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"farmMechanics","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"farmingAssets","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAssetsProportions","outputs":[{"internalType":"uint256[]","name":"proportions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRevenue","outputs":[{"internalType":"address[]","name":"__assets","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getSpecificName","outputs":[{"internalType":"string","name":"","type":"string"},{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"platform_","type":"address"}],"name":"initVariants","outputs":[{"internalType":"string[]","name":"variants","type":"string[]"},{"internalType":"address[]","name":"addresses","type":"address[]"},{"internalType":"uint256[]","name":"nums","type":"uint256[]"},{"internalType":"int24[]","name":"ticks","type":"int24[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"addresses","type":"address[]"},{"internalType":"uint256[]","name":"nums","type":"uint256[]"},{"internalType":"int24[]","name":"ticks","type":"int24[]"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isHardWorkOnDepositAllowed","outputs":[{"internalType":"bool","name":"allowed","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"isReadyForHardWork","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastApr","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastAprCompound","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastHardWork","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"platform","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256[]","name":"amountsMax","type":"uint256[]"}],"name":"previewDepositAssets","outputs":[{"internalType":"uint256[]","name":"amountsConsumed","type":"uint256[]"},{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256[]","name":"amountsMax","type":"uint256[]"}],"name":"previewDepositAssetsWrite","outputs":[{"internalType":"uint256[]","name":"amountsConsumed","type":"uint256[]"},{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"refreshFarmingAssets","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakingPool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"strategyLogicId","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"supportedVaultTypes","outputs":[{"internalType":"string[]","name":"types","type":"string[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"total","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"total_","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"transferAssets","outputs":[{"internalType":"uint256[]","name":"amountsOut","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"underlying","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"withdrawAssets","outputs":[{"internalType":"uint256[]","name":"amountsOut","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"withdrawUnderlying","outputs":[],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
608060405234801562000010575f80fd5b506200001b62000021565b620000d5565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff1615620000725760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b0390811614620000d25780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b615c4e80620000e35f395ff3fe608060405234801561000f575f80fd5b5060043610610281575f3560e01c80636f307dc311610156578063aa47f4e1116100ca578063f2c33e2d11610084578063f2c33e2d14610579578063f815c4ff1461059d578063f985b0bc146105a5578063fbfa77cf146105b8578063fdff667c146105c0578063ffa1ad7414610499575f80fd5b8063aa47f4e11461051a578063aefb075114610522578063b600585a14610545578063b6c8cdef14610558578063b9f5be411461055e578063f1faf05014610571575f80fd5b80638a7f53601161011b5780638a7f536014610491578063936725ec146104995780639736374e146104bd57806399f428cf146104c45780639b3ff191146104d7578063a2b7722c14610507575f80fd5b80636f307dc31461045c57806371a97305146104645780637284e4161461047957806374bac4291461048157806380e7ac7c14610489575f80fd5b806341affeb8116101f857806350f4e419116101b257806350f4e419146103df57806359498ab7146103ff5780635b0f088a1461040757806367cf905a1461042b57806367fde573146104335780636d9894391461043b575f80fd5b806341affeb8146103835780634593144c146103965780634875c9681461039e57806348d7d9eb146103a65780634bde38c8146103cf5780634fa5d854146103d7575f80fd5b80631ec71e05116102495780631ec71e05146102f3578063278de000146103095780632a8ba2931461031d5780632d433b281461034e5780632ddbd13a14610371578063394f523214610379575f80fd5b806301ffc9a7146102855780630c56ae3b146102ad57806313e63180146102cd57806316f0115b146102e3578063190024e0146102eb575b5f80fd5b6102986102933660046147fe565b6105d5565b60405190151581526020015b60405180910390f35b6102b56105e5565b6040516001600160a01b0390911681526020016102a4565b6102d5610616565b6040519081526020016102a4565b6102b5610628565b6102d5610647565b6102fb6106e9565b6040516102a4929190614872565b5f80516020615bf9833981519152546102d5565b610341604051806040016040528060058152602001640312e322e360dc1b81525081565b6040516102a49190614895565b61036161035c3660046148bb565b6108b3565b6040516102a494939291906149a0565b6102d5610cac565b610381610cbe565b005b610381610391366004614b8f565b610d51565b6102d56110f3565b610341611126565b6103c1604080515f8082526020820190815281830190925291565b6040516102a4929190614c6d565b6102b561114f565b61038161117e565b6103f26103ed366004614c91565b61143b565b6040516102a49190614ce7565b6103c161145a565b610341604051806040016040528060058152602001640322e302e360dc1b81525081565b6103f26114ec565b6103816115d7565b61044e610449366004614cf9565b6115f3565b6040516102a4929190614d58565b6102b56116f8565b61046c611713565b6040516102a49190614d79565b61034161177c565b610298611899565b6102986118a9565b6103416118bb565b610341604051806040016040528060058152602001640312e302e360dc1b81525081565b6001610298565b6103816104d2366004614d8b565b6118de565b7fa6fdc931ca23c69f54119a0a2d6478619b5aa365084590a1fbc287668fbabe01546001600160a01b03166102b5565b6102d5610515366004614db9565b6118f4565b61046c61192e565b604080518082019091526007815266436c617373696360c81b6020820152610341565b61044e610553366004614cf9565b61199b565b5f610298565b6103f261056c366004614dea565b611a8d565b6102d5611aa0565b610341604051806040016040528060058152602001640c4b8c0b8d60da1b81525081565b6102d5611ab2565b6103f26105b3366004614e01565b611ac4565b6102b5611b6d565b6105c8611b76565b6040516102a49190614e2c565b5f6105df82611be8565b92915050565b5f806105ef611c0c565b9050806080015160018151811061060857610608614e3e565b602002602001015191505090565b5f61061f611c33565b60020154905090565b5f5f80516020615bd98339815191525b546001600160a01b0316919050565b6040805162965fff60e81b60208201525f6023820181905282516006818403018152602683019384905263bfe370d960e01b90935291734f76add676c04eca837130ceb58bc173de8799de9163bfe370d9916106a591602a01614895565b602060405180830381865af41580156106c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106e49190614e52565b905090565b60605f806106f5611c0c565b90505f81608001515f8151811061070e5761070e614e3e565b602002602001015190505f816001600160a01b0316637f7a1eec6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610755573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107799190614e78565b6107e257816001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107b9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107dd9190614e9c565b610842565b816001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa15801561081e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108429190614e9c565b90505f816001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015610880573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526108a79190810190614f17565b965f9650945050505050565b6060806060805f856001600160a01b0316634254af1c6108d16118bb565b805190602001206040518263ffffffff1660e01b81526004016108f691815260200190565b5f60405180830381865afa158015610910573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526109379190810190614f48565b602090810151604080515f80825281850181815282840180855263c45a015560e01b90529251919850919550919350916001600160a01b0389169163c45a0155916044808a019290818b030181865afa158015610996573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109ba9190614e9c565b6001600160a01b031663871fd6826040518163ffffffff1660e01b81526004015f60405180830381865afa1580156109f4573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610a1b91908101906151f3565b80519091505f805b82811015610af2575f848281518110610a3e57610a3e614e3e565b60200260200101519050805f01515f148015610ad85750734f76add676c04eca837130ceb58bc173de8799de6321a496428260400151610a7c611126565b6040518363ffffffff1660e01b8152600401610a9992919061529c565b602060405180830381865af4158015610ab4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ad89190614e78565b15610ae957610ae6836152d4565b92505b50600101610a23565b50806001600160401b03811115610b0b57610b0b614a22565b604051908082528060200260200182016040528015610b3e57816020015b6060815260200190600190039081610b295790505b509750806001600160401b03811115610b5957610b59614a22565b604051908082528060200260200182016040528015610b82578160200160208202803683370190505b5095505f90505f5b82811015610ca0575f848281518110610ba557610ba5614e3e565b60200260200101519050805f01515f148015610c3f5750734f76add676c04eca837130ceb58bc173de8799de6321a496428260400151610be3611126565b6040518363ffffffff1660e01b8152600401610c0092919061529c565b602060405180830381865af4158015610c1b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c3f9190614e78565b15610c975781888481518110610c5757610c57614e3e565b602002602001018181525050610c6d8187611c57565b8a8481518110610c7f57610c7f614e3e565b602002602001018190525082610c94906152d4565b92505b50600101610b8a565b50505050509193509193565b5f610cb5611c33565b60010154905090565b610cc6611f42565b73e347a67358dd7cba1eb146b9a60172a10cb8abee63fede401f5f80516020615bf9833981519152610cf661114f565b6040516001600160e01b031960e085901b16815260048101929092526001600160a01b031660248201526044015f6040518083038186803b158015610d39575f80fd5b505af4158015610d4b573d5f803e3d5ffd5b50505050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff1615906001600160401b03165f81158015610d955750825b90505f826001600160401b03166001148015610db05750303b155b905081158015610dbe575080155b15610ddc5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610e0657845460ff60401b1916600160401b1785555b87516002141580610e1957508651600114155b80610e245750855115155b15610e42576040516363cf6b6160e01b815260040160405180910390fd5b5f610e7f895f81518110610e5857610e58614e3e565b6020026020010151895f81518110610e7257610e72614e3e565b6020026020010151611fd1565b90508060800151516002141580610e9a575060a08101515115155b80610ea9575060c08101515115155b15610ec7576040516325b769d160e11b815260040160405180910390fd5b610f956040518060a001604052806040518060400160405280600f81526020016e49636869205377617058204661726d60881b81525081526020018b5f81518110610f1457610f14614e3e565b60200260200101516001600160a01b031681526020018b600181518110610f3d57610f3d614e3e565b60200260200101516001600160a01b0316815260200183602001516001600160a01b0316815260200183608001515f81518110610f7c57610f7c614e3e565b60200260200101516001600160a01b03168152506120a7565b610fd1895f81518110610faa57610faa614e3e565b6020026020010151895f81518110610fc457610fc4614e3e565b6020026020010151612171565b5f610fda611713565b905061103182608001515f81518110610ff557610ff5614e3e565b60200260200101515f19835f8151811061101157611011614e3e565b60200260200101516001600160a01b03166121fd9092919063ffffffff16565b61106782608001515f8151811061104a5761104a614e3e565b60200260200101515f198360018151811061101157611011614e3e565b6110a1826080015160018151811061108157611081614e3e565b60200260200101515f1984608001515f8151811061101157611011614e3e565b505083156110e957845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050565b5f6106e461112260017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f16152ec565b5490565b60408051808201909152600f81526e49636869205377617058204661726d60881b602082015290565b5f6106e461112260017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d66152ec565b6111866122ba565b61118e6122eb565b5f611197611c33565b805460408051637299470360e11b815281519394506001600160a01b03909216925f92849263e5328e06926004808401938290030181865afa1580156111df573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061120391906152ff565b5090508015611436575f61121561114f565b60088501549091505f808080611229612368565b93509350935093505f6112395f90565b61133d5761126185878151811061125257611252614e3e565b6020026020010151848461271f565b84878151811061127357611273614e3e565b602002602001018181516112879190615329565b915081815250505f73e347a67358dd7cba1eb146b9a60172a10cb8abee6356cd528e898c8e6007018a8a6040518663ffffffff1660e01b81526004016112d19594939291906153ed565b5f60405180830381865af41580156112eb573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611312919081019061543e565b90505f61131f87836127a3565b90508b600101549250801561133657611336612871565b50506113c1565b6040516336ac731760e11b81526001600160a01b038a1690636d58e62e9061136b9088908890600401614c6d565b5f604051808303815f87803b158015611382575f80fd5b505af1158015611394573d5f803e3d5ffd5b505050506113ad855f8151811061125257611252614e3e565b506113b885856127a3565b506113c1612871565b60405163640f244560e01b815273e347a67358dd7cba1eb146b9a60172a10cb8abee9063640f244590611402908d908b908a908a908f90899060040161546f565b5f6040518083038186803b158015611418575f80fd5b505af415801561142a573d5f803e3d5ffd5b50505050505050505050505b505050565b60606114456122ba565b61145084848461290a565b90505b9392505050565b606080611465612982565b604051633f8b51a560e21b8152919350915073e347a67358dd7cba1eb146b9a60172a10cb8abee9063fe2d4694906114a39085908590600401614c6d565b5f60405180830381865af41580156114bd573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526114e491908101906154c0565b915091509091565b60605f6114f7611c33565b60068101546040805160028082526060820183529394506001600160a01b039092169290602083019080368337019050509250806001600160a01b0316637f7a1eec6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611566573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061158a9190614e78565b156115bb57670de0b6b3a7640000835f815181106115aa576115aa614e3e565b602002602001018181525050505090565b670de0b6b3a7640000836001815181106115aa576115aa614e3e565b6115df612b57565b6115f06115ea610cac565b30612c72565b50565b60605f8351600114801561163f575061160a611c33565b6006015484516001600160a01b039091169085905f9061162c5761162c614e3e565b60200260200101516001600160a01b0316145b801561167657505f6001600160a01b0316845f8151811061166257611662614e3e565b60200260200101516001600160a01b031614155b156116e257825160011461169d57604051630ef9926760e21b815260040160405180910390fd5b825f815181106116af576116af614e3e565b602002602001015190506116db835f815181106116ce576116ce614e3e565b6020026020010151612e2f565b91506116f1565b6116ec8484612e3a565b915091505b9250929050565b5f611701611c33565b600601546001600160a01b0316919050565b606061171d611c33565b60050180548060200260200160405190810160405280929190818152602001828054801561177257602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311611754575b5050505050905090565b60605f80516020615bf98339815191525f80516020615bd98339815191525f6117a361114f565b6001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117de573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118029190614e9c565b835460405163538a85a160e01b81526001600160a01b03929092169163538a85a1916118349160040190815260200190565b5f60405180830381865afa15801561184e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526118759190810190615515565b60018301549091506118919082906001600160a01b0316611c57565b935050505090565b5f6118a2610cac565b1515919050565b5f806118b3611c0c565b511592915050565b604080518082019091526009815268105b19d9589c98558d60ba1b602082015290565b6118e66122ba565b6118f08282612e47565b5050565b5f6118fd6122ba565b5f611906611c33565b905080600201545f0361191a574260028201555b611925836001612f2f565b9150505b919050565b60605f80516020615bf983398151915260010180548060200260200160405190810160405280929190818152602001828054801561177257602002820191905f5260205f209081546001600160a01b03168152600190910190602001808311611754575050505050905090565b60605f835160011480156119e757506119b2611c33565b6006015484516001600160a01b039091169085905f906119d4576119d4614e3e565b60200260200101516001600160a01b0316145b8015611a1e57505f6001600160a01b0316845f81518110611a0a57611a0a614e3e565b60200260200101516001600160a01b031614155b15611a83578251600114611a4557604051630ef9926760e21b815260040160405180910390fd5b825f81518110611a5757611a57614e3e565b602002602001015190506116db835f81518110611a7657611a76614e3e565b60200260200101516130a2565b6116ec8484613218565b6060611a976122ba565b6105df82613292565b5f611aa9611c33565b60040154905090565b5f611abb611c33565b60030154905090565b6060611ace6122ba565b73e347a67358dd7cba1eb146b9a60172a10cb8abee6325567aef611af0611c33565b6040516001600160e01b031960e084901b168152600481019190915260248101879052604481018690526001600160a01b03851660648201526084015f60405180830381865af4158015611b46573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611450919081019061543e565b5f610638611c33565b604080516001808252818301909252606091816020015b6060815260200190600190039081611b8d5790505090506040518060400160405280600b81526020016a436f6d706f756e64696e6760a81b815250815f81518110611bda57611bda614e3e565b602002602001018190525090565b5f6001600160e01b031982166396cf43c560e01b14806105df57506105df8261334e565b611c1461474c565b6106e4611c1f61114f565b5f80516020615bf983398151915254611fd1565b7fb14b643f49bed6a2c6693bbd50f68dc950245db265c66acadbfa51ccc8c3ba0090565b6060734f76add676c04eca837130ceb58bc173de8799de631dfab928734f76add676c04eca837130ceb58bc173de8799de63fbcadbe986606001516040518263ffffffff1660e01b8152600401611cae9190614d79565b5f60405180830381865af4158015611cc8573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611cef9190810190615546565b6040518263ffffffff1660e01b8152600401611d0b919061562d565b5f60405180830381865af4158015611d25573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611d4c9190810190614f17565b602084015160405163a912616960e01b81526001600160a01b039182166004820152734f76add676c04eca837130ceb58bc173de8799de91631dfab92891839163fbcadbe9919088169063a9126169906024015f60405180830381865afa158015611db9573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611de09190810190615663565b6040518263ffffffff1660e01b8152600401611dfc9190614d79565b5f60405180830381865af4158015611e16573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611e3d9190810190615546565b6040518263ffffffff1660e01b8152600401611e599190615694565b5f60405180830381865af4158015611e73573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611e9a9190810190614f17565b84608001515f81518110611eb057611eb0614e3e565b60200260200101516001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015611ef2573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611f199190810190614f17565b604051602001611f2b939291906156c9565b604051602081830303815290604052905092915050565b611f4a61114f565b6040516336b87bd760e11b81523360048201526001600160a01b039190911690636d70f7ae90602401602060405180830381865afa158015611f8e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fb29190614e78565b611fcf57604051631f0853c160e21b815260040160405180910390fd5b565b611fd961474c565b826001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015612015573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120399190614e9c565b6001600160a01b031663538a85a1836040518263ffffffff1660e01b815260040161206691815260200190565b5f60405180830381865afa158015612080573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526114539190810190615515565b6120af613372565b5f5f80516020615bd9833981519152905060605f73f732df3f82d1ce0234bf5ee6933fd370b8b30f2a638ff2a774848660200151876120ec6118bb565b6040518563ffffffff1660e01b815260040161210b949392919061575c565b5f60405180830381865af4158015612125573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261214c91908101906157d2565b8092508193505050610d4b8460200151855f01518660400151858860800151866133bb565b612179613372565b73e347a67358dd7cba1eb146b9a60172a10cb8abee634ab3b02f5f80516020615bf98339815191526121a9611c33565b60070185856040518563ffffffff1660e01b81526004016121cd9493929190615815565b5f6040518083038186803b1580156121e3575f80fd5b505af41580156121f5573d5f803e3d5ffd5b505050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261224e848261345f565b610d4b576040516001600160a01b0384811660248301525f60448301526122b091869182169063095ea7b3906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050613500565b610d4b8482613500565b6122c2611c33565b546001600160a01b03163314611fcf576040516362df054560e01b815260040160405180910390fd5b306001600160a01b03166374bac4296040518163ffffffff1660e01b8152600401602060405180830381865afa158015612327573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061234b9190614e78565b611fcf576040516309ea311f60e11b815260040160405180910390fd5b606080606080612376611713565b935083516001600160401b0381111561239157612391614a22565b6040519080825280602002602001820160405280156123ba578160200160208202803683370190505b507fe61f0a7b2953b9e28e48cc07562ad7979478dcaee972e68dcf3b10da2cba60018054604080516020808402820181019092528281529396505f80516020615bf98339815191529392919083018282801561243d57602002820191905f5260205f20905b81546001600160a01b0316815260019091019060200180831161241f575b505050505092505f73e347a67358dd7cba1eb146b9a60172a10cb8abee63e3d670d7855f8151811061247157612471614e3e565b60200260200101516040518263ffffffff1660e01b81526004016124a491906001600160a01b0391909116815260200190565b602060405180830381865af41580156124bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124e39190614e52565b604080516001808252818301909252919250602080830190803683370190505092505f61250e611c0c565b90505f816080015160018151811061252857612528614e3e565b60200260200101516001600160a01b0316637c91e4eb6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561256b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061258f9190614e9c565b6040805160018082528183019092529192505f91906020808301908036833701905050905082608001516001815181106125cb576125cb614e3e565b6020026020010151815f815181106125e5576125e5614e3e565b6001600160a01b03928316602091820292909201015260405163f9f031df60e01b81529083169063f9f031df90612620908490600401614d79565b5f604051808303815f87803b158015612637575f80fd5b505af1158015612649573d5f803e3d5ffd5b505050508373e347a67358dd7cba1eb146b9a60172a10cb8abee63e3d670d7895f8151811061267a5761267a614e3e565b60200260200101516040518263ffffffff1660e01b81526004016126ad91906001600160a01b0391909116815260200190565b602060405180830381865af41580156126c8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126ec9190614e52565b6126f691906152ec565b865f8151811061270857612708614e3e565b602002602001018181525050505050505090919293565b5f73e347a67358dd7cba1eb146b9a60172a10cb8abee6374e714c861274261114f565b8686866040518563ffffffff1660e01b81526004016127649493929190615849565b602060405180830381865af415801561277f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114509190614e52565b5f5f80516020615bd983398151915273f732df3f82d1ce0234bf5ee6933fd370b8b30f2a6372d46b086127d461114f565b6127dc611b6d565b60018501546001600160a01b03166127f2611c33565b6008015486546040516001600160e01b031960e088901b16815261282a95949392916001600160a01b0316908c908c90600401615891565b602060405180830381865af4158015612845573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128699190614e78565b949350505050565b5f61287a6114ec565b90505f61289f825f8151811061289257612892614e3e565b6020026020010151613566565b90506001815f815181106128b5576128b5614e3e565b602002602001015111806128e357506001816001815181106128d9576128d9614e3e565b6020026020010151115b156118f0575f6128f282613616565b9092509050600a81111561143657610d4b825f612f2f565b606073f732df3f82d1ce0234bf5ee6933fd370b8b30f2a639dfc419f8561292f611713565b6040518363ffffffff1660e01b815260040161294c9291906158f3565b5f6040518083038186803b158015612962575f80fd5b505af4158015612974573d5f803e3d5ffd5b505050506114508383612c72565b6060805f61298e611c33565b600581018054604080516020808402820181019092528281529394508301828280156129e157602002820191905f5260205f20905b81546001600160a01b031681526001909101906020018083116129c3575b505050506001830154600684015460408051636253bb0f60e11b8152815195985092946001600160a01b0390921693505f928392859263c4a7761e92600480820193918290030181865afa158015612a3b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a5f9190615917565b915091505f836001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612aa0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ac49190614e52565b604080516002808252606082018352929350919060208301908036833701905050965080612af28685615939565b612afc9190615950565b875f81518110612b0e57612b0e614e3e565b602090810291909101015280612b248684615939565b612b2e9190615950565b87600181518110612b4157612b41614e3e565b6020026020010181815250505050505050509091565b5f612b6061114f565b9050336001600160a01b0316816001600160a01b0316635aa6e6756040518163ffffffff1660e01b8152600401602060405180830381865afa158015612ba8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bcc9190614e9c565b6001600160a01b031614158015612c545750336001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c24573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c489190614e9c565b6001600160a01b031614155b156115f0576040516354299b6f60e01b815260040160405180910390fd5b60605f612c7d611c0c565b90508060800151600181518110612c9657612c96614e3e565b60200260200101516001600160a01b0316632e1a7d4d856040518263ffffffff1660e01b8152600401612ccb91815260200190565b5f604051808303815f87803b158015612ce2575f80fd5b505af1158015612cf4573d5f803e3d5ffd5b5060029250612d01915050565b604051908082528060200260200182016040528015612d2a578160200160208202803683370190505b50915080608001515f81518110612d4357612d43614e3e565b60200260200101516001600160a01b031662f714ce85856040518363ffffffff1660e01b8152600401612d899291909182526001600160a01b0316602082015260400190565b60408051808303815f875af1158015612da4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612dc89190615917565b835f81518110612dda57612dda614e3e565b6020026020010184600181518110612df457612df4614e3e565b6020908102919091010191909152525f612e0c611c33565b905084816001015f828254612e2191906152ec565b909155509295945050505050565b60606105df826130a2565b60605f6116ec8484613218565b5f612e50611c0c565b90508060800151600181518110612e6957612e69614e3e565b60200260200101516001600160a01b0316632e1a7d4d846040518263ffffffff1660e01b8152600401612e9e91815260200190565b5f604051808303815f87803b158015612eb5575f80fd5b505af1158015612ec7573d5f803e3d5ffd5b50505050612f06828483608001515f81518110612ee657612ee6614e3e565b60200260200101516001600160a01b0316613d409092919063ffffffff16565b5f612f0f611c33565b905083816001015f828254612f2491906152ec565b909155505050505050565b5f80612f39611c0c565b905080608001515f81518110612f5157612f51614e3e565b60200260200101516001600160a01b0316638dbdbe6d855f81518110612f7957612f79614e3e565b602002602001015186600181518110612f9457612f94614e3e565b60209081029190910101516040516001600160e01b031960e085901b168152600481019290925260248201523060448201526064016020604051808303815f875af1158015612fe5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130099190614e52565b9150806080015160018151811061302257613022614e3e565b60200260200101516001600160a01b031663b6b55f25836040518263ffffffff1660e01b815260040161305791815260200190565b5f604051808303815f87803b15801561306e575f80fd5b505af1158015613080573d5f803e3d5ffd5b505050505f61308d611c33565b905082816001015f828254612e219190615329565b60605f6130ad611c33565b600681015460408051636253bb0f60e11b815281519394506001600160a01b03909216925f928392859263c4a7761e9260048082019392918290030181865afa1580156130fc573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131209190615917565b915091505f836001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613161573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131859190614e52565b6040805160028082526060820183529293509190602083019080368337019050509550806131b38885615939565b6131bd9190615950565b865f815181106131cf576131cf614e3e565b6020908102919091010152806131e58884615939565b6131ef9190615950565b8660018151811061320257613202614e3e565b6020026020010181815250505050505050919050565b60605f73f732df3f82d1ce0234bf5ee6933fd370b8b30f2a639d186c788561323e611713565b866040518463ffffffff1660e01b815260040161325d9392919061596f565b5f6040518083038186803b158015613273575f80fd5b505af4158015613285573d5f803e3d5ffd5b505050506116ec83613616565b60605f61329d611c0c565b905080608001516001815181106132b6576132b6614e3e565b60200260200101516001600160a01b031663b6b55f25846040518263ffffffff1660e01b81526004016132eb91815260200190565b5f604051808303815f87803b158015613302575f80fd5b505af1158015613314573d5f803e3d5ffd5b50505050613321836130a2565b91505f61332c611c33565b905083816001015f8282546133419190615329565b9091555092949350505050565b5f6001600160e01b031982166303d859d560e11b14806105df57506105df82613d71565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16611fcf57604051631afcd79f60e31b815260040160405180910390fd5b6133c3613372565b6133cc86613d95565b5f6133d5611c33565b600881018390556006810180546001600160a01b0319166001600160a01b03861617905584519091508690869086908690869060078701905f908890829061342690600584019060208a0190614790565b5081546001600160a01b03808a166101009390930a928302920219161790555061345086826159f2565b50505050505050505050505050565b5f805f846001600160a01b03168460405161347a9190615aad565b5f604051808303815f865af19150503d805f81146134b3576040519150601f19603f3d011682016040523d82523d5f602084013e6134b8565b606091505b50915091508180156134e25750805115806134e25750808060200190518101906134e29190614e78565b80156134f757505f856001600160a01b03163b115b95945050505050565b5f6135146001600160a01b03841683613ef0565b905080515f141580156135385750808060200190518101906135369190614e78565b155b1561143657604051635274afe760e01b81526001600160a01b03841660048201526024015b60405180910390fd5b60605f80516020615bd983398151915273f732df3f82d1ce0234bf5ee6933fd370b8b30f2a633f9406db61359861114f565b600184015484546001600160a01b0391821691166135b4611713565b886040518663ffffffff1660e01b81526004016135d5959493929190615ac8565b5f60405180830381865af41580156135ef573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611925919081019061543e565b60605f80613622611c33565b60068101546040805160028082526060820183529394506001600160a01b039092169290602083019080368337019050509350806001600160a01b0316637f7a1eec6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613691573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136b59190614e78565b156136f757845f815181106136cc576136cc614e3e565b6020026020010151845f815181106136e6576136e6614e3e565b602002602001018181525050613732565b8460018151811061370a5761370a614e3e565b60200260200101518460018151811061372557613725614e3e565b6020026020010181815250505b60408051610140810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810191909152816001600160a01b03166316f0115b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137be573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137e29190614e9c565b8160e001906001600160a01b031690816001600160a01b031681525050816001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa15801561383b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061385f9190614e9c565b8161010001906001600160a01b031690816001600160a01b031681525050816001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138b9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138dd9190614e9c565b8161012001906001600160a01b031690816001600160a01b031681525050816001600160a01b031663f62073266040518163ffffffff1660e01b8152600401602060405180830381865afa158015613937573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061395b9190615b0d565b63ffffffff16815260408051630dfe168160e01b81529051613a9d916001600160a01b03851691630dfe1681916004808201926020929091908290030181865afa1580156139ab573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139cf9190614e9c565b836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa158015613a0b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a2f9190614e9c565b846001600160a01b031663065e53606040518163ffffffff1660e01b8152600401602060405180830381865afa158015613a6b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a8f9190615b30565b670de0b6b3a7640000613efd565b604082015260e08101516101008201516101208301518351613aca93929190670de0b6b3a7640000613f12565b816060018181525050816001600160a01b03166391563d326040518163ffffffff1660e01b8152600401602060405180830381865afa158015613b0f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b339190615b0d565b63ffffffff1660208201819052613b4e578060600151613b75565b613b758160e001518261010001518361012001518460200151670de0b6b3a7640000613f12565b8160800181815250505f80836001600160a01b031663c4a7761e6040518163ffffffff1660e01b81526004016040805180830381865afa158015613bbb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613bdf9190615917565b915091505f613c018460400151856060015186608001515f8860200151613fcd565b90505f670de0b6b3a7640000828a5f81518110613c2057613c20614e3e565b6020026020010151613c329190615939565b613c3c9190615950565b90508089600181518110613c5257613c52614e3e565b6020026020010151613c649190615329565b97505f866001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613ca3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613cc79190614e52565b90508015613d33575f613cee87604001518860600151896080015160018b60200151613fcd565b90505f670de0b6b3a7640000613d048389615939565b613d0e9190615950565b9050613d1a8682615329565b613d24848d615939565b613d2e9190615950565b9a5050505b5050505050505050915091565b6040516001600160a01b0383811660248301526044820183905261143691859182169063a9059cbb9060640161227e565b5f6001600160e01b031982166342c352d360e11b14806105df57506105df8261402d565b613d9d613372565b6001600160a01b0381161580613e2357505f6001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613df4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613e189190614e9c565b6001600160a01b0316145b15613e41576040516371c42ac360e01b815260040160405180910390fd5b613e74613e6f60017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d66152ec565b829055565b613ea643613ea360017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f16152ec565b55565b604080516001600160a01b0383168152426020820152438183015290517f1a2dd071001ebf6e03174e3df5b305795a4ad5d41d8fdb9ba41dbbe2367134269181900360600190a150565b606061145383835f614061565b5f6134f783613f0b846140fa565b8787614131565b5f80613f1d876144e5565b604051638241348960e01b81526001600160a01b038216600482015263ffffffff861660248201529091505f9073e3c14573ccd72f95a739f297dcfa8d525aa330ac90638241348990604401602060405180830381865af4158015613f84573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613fa89190615b30565b60020b9050613fc181613fba866140fa565b8989614131565b98975050505050505050565b5f82156140045763ffffffff821615613ffa57613ff3613fed8787614597565b85614597565b90506134f7565b613ff38686614597565b63ffffffff82161561402357613ff361401d87876145ac565b856145ac565b613ff386866145ac565b5f6001600160e01b03198216630f1ec81f60e41b14806105df57506301ffc9a760e01b6001600160e01b03198316146105df565b6060814710156140865760405163cd78605960e01b815230600482015260240161355d565b5f80856001600160a01b031684866040516140a19190615aad565b5f6040518083038185875af1925050503d805f81146140db576040519150601f19603f3d011682016040523d82523d5f602084013e6140e0565b606091505b50915091506140f08683836145ba565b9695505050505050565b5f6001600160801b0382111561412d576040516306dfcc6560e41b8152608060048201526024810183905260440161355d565b5090565b60405163986cfba360e01b8152600285900b60048201525f90819073bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063986cfba390602401602060405180830381865af4158015614186573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906141aa9190614e9c565b90506001600160801b036001600160a01b03821611614315575f6141d76001600160a01b03831680615939565b9050836001600160a01b0316856001600160a01b0316106142825760405163554d048960e11b8152600160c01b60048201526001600160801b03871660248201526044810182905273bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af4158015614259573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061427d9190614e52565b61430d565b60405163554d048960e11b8152600481018290526001600160801b0387166024820152600160c01b604482015273bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af41580156142e9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061430d9190614e52565b9250506144dc565b60405163554d048960e11b81526001600160a01b038216600482018190526024820152600160401b60448201525f9073bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af415801561437e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143a29190614e52565b9050836001600160a01b0316856001600160a01b03161061444d5760405163554d048960e11b8152600160801b60048201526001600160801b03871660248201526044810182905273bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af4158015614424573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906144489190614e52565b6144d8565b60405163554d048960e11b8152600481018290526001600160801b0387166024820152600160801b604482015273bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af41580156144b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906144d89190614e52565b9250505b50949350505050565b5f816001600160a01b031663ef01df4f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015614522573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906145469190614e9c565b90506145528183614616565b6119295760405162461bcd60e51b815260206004820152601660248201527524ab1d103234b1b7b73732b1ba32b21038363ab3b4b760511b604482015260640161355d565b5f8183116145a55781611453565b5090919050565b5f8183106145a55781611453565b6060826145cf576145ca82614723565b611453565b81511580156145e657506001600160a01b0384163b155b1561460f57604051639996b31560e01b81526001600160a01b038516600482015260240161355d565b5080611453565b5f6001600160a01b03831661462c57505f6105df565b5f829050806001600160a01b031663ef01df4f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561466c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906146909190614e9c565b6001600160a01b0316846001600160a01b03160361471c575f816001600160a01b031663e76c01e46040518163ffffffff1660e01b815260040160c060405180830381865afa1580156146e5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906147099190615b5c565b505093505050506134f781600116151590565b5092915050565b8051156147335780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b6040518060e001604052805f81526020015f6001600160a01b0316815260200160608152602001606081526020016060815260200160608152602001606081525090565b828054828255905f5260205f209081019282156147e3579160200282015b828111156147e357825182546001600160a01b0319166001600160a01b039091161782556020909201916001909101906147ae565b5061412d9291505b8082111561412d575f81556001016147eb565b5f6020828403121561480e575f80fd5b81356001600160e01b031981168114611453575f80fd5b5f5b8381101561483f578181015183820152602001614827565b50505f910152565b5f815180845261485e816020860160208601614825565b601f01601f19169290920160200192915050565b604081525f6148846040830185614847565b905082151560208301529392505050565b602081525f6114536020830184614847565b6001600160a01b03811681146115f0575f80fd5b5f602082840312156148cb575f80fd5b8135611453816148a7565b5f8282518085526020808601955060208260051b840101602086015f5b8481101561492157601f1986840301895261490f838351614847565b988401989250908301906001016148f3565b5090979650505050505050565b5f815180845260208085019450602084015f5b838110156149665781516001600160a01b031687529582019590820190600101614941565b509495945050505050565b5f815180845260208085019450602084015f5b8381101561496657815187529582019590820190600101614984565b608081525f6149b260808301876148d6565b602083820360208501526149c6828861492e565b915083820360408501526149da8287614971565b8481036060860152855180825260208088019450909101905f5b81811015614a1357845160020b835293830193918301916001016149f4565b50909998505050505050505050565b634e487b7160e01b5f52604160045260245ffd5b60405160e081016001600160401b0381118282101715614a5857614a58614a22565b60405290565b604051601f8201601f191681016001600160401b0381118282101715614a8657614a86614a22565b604052919050565b5f6001600160401b03821115614aa657614aa6614a22565b5060051b60200190565b5f82601f830112614abf575f80fd5b81356020614ad4614acf83614a8e565b614a5e565b8083825260208201915060208460051b870101935086841115614af5575f80fd5b602086015b84811015614b1a578035614b0d816148a7565b8352918301918301614afa565b509695505050505050565b5f82601f830112614b34575f80fd5b81356020614b44614acf83614a8e565b8083825260208201915060208460051b870101935086841115614b65575f80fd5b602086015b84811015614b1a5780358352918301918301614b6a565b8060020b81146115f0575f80fd5b5f805f60608486031215614ba1575f80fd5b83356001600160401b0380821115614bb7575f80fd5b614bc387838801614ab0565b9450602091508186013581811115614bd9575f80fd5b614be588828901614b25565b945050604086013581811115614bf9575f80fd5b86019050601f81018713614c0b575f80fd5b8035614c19614acf82614a8e565b81815260059190911b82018301908381019089831115614c37575f80fd5b928401925b82841015614c5e578335614c4f81614b81565b82529284019290840190614c3c565b80955050505050509250925092565b604081525f614c7f604083018561492e565b82810360208401526134f78185614971565b5f805f60608486031215614ca3575f80fd5b83356001600160401b03811115614cb8575f80fd5b614cc486828701614ab0565b935050602084013591506040840135614cdc816148a7565b809150509250925092565b602081525f6114536020830184614971565b5f8060408385031215614d0a575f80fd5b82356001600160401b0380821115614d20575f80fd5b614d2c86838701614ab0565b93506020850135915080821115614d41575f80fd5b50614d4e85828601614b25565b9150509250929050565b604081525f614d6a6040830185614971565b90508260208301529392505050565b602081525f611453602083018461492e565b5f8060408385031215614d9c575f80fd5b823591506020830135614dae816148a7565b809150509250929050565b5f60208284031215614dc9575f80fd5b81356001600160401b03811115614dde575f80fd5b61286984828501614b25565b5f60208284031215614dfa575f80fd5b5035919050565b5f805f60608486031215614e13575f80fd5b83359250602084013591506040840135614cdc816148a7565b602081525f61145360208301846148d6565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215614e62575f80fd5b5051919050565b80518015158114611929575f80fd5b5f60208284031215614e88575f80fd5b61145382614e69565b8051611929816148a7565b5f60208284031215614eac575f80fd5b8151611453816148a7565b5f82601f830112614ec6575f80fd5b81516001600160401b03811115614edf57614edf614a22565b614ef2601f8201601f1916602001614a5e565b818152846020838601011115614f06575f80fd5b612869826020830160208701614825565b5f60208284031215614f27575f80fd5b81516001600160401b03811115614f3c575f80fd5b61286984828501614eb7565b5f60208284031215614f58575f80fd5b81516001600160401b0380821115614f6e575f80fd5b9083019060408286031215614f81575f80fd5b604051604081018181108382111715614f9c57614f9c614a22565b604052825182811115614fad575f80fd5b614fb987828601614eb7565b82525060208301519250614fcc836148a7565b6020810192909252509392505050565b5f82601f830112614feb575f80fd5b81516020614ffb614acf83614a8e565b8083825260208201915060208460051b87010193508684111561501c575f80fd5b602086015b84811015614b1a578051615034816148a7565b8352918301918301615021565b5f82601f830112615050575f80fd5b81516020615060614acf83614a8e565b8083825260208201915060208460051b870101935086841115615081575f80fd5b602086015b84811015614b1a5780518352918301918301615086565b5f82601f8301126150ac575f80fd5b815160206150bc614acf83614a8e565b8083825260208201915060208460051b8701019350868411156150dd575f80fd5b602086015b84811015614b1a5780516150f581614b81565b83529183019183016150e2565b5f60e08284031215615112575f80fd5b61511a614a36565b90508151815261512c60208301614e91565b602082015260408201516001600160401b038082111561514a575f80fd5b61515685838601614eb7565b6040840152606084015191508082111561516e575f80fd5b61517a85838601614fdc565b60608401526080840151915080821115615192575f80fd5b61519e85838601614fdc565b608084015260a08401519150808211156151b6575f80fd5b6151c285838601615041565b60a084015260c08401519150808211156151da575f80fd5b506151e78482850161509d565b60c08301525092915050565b5f6020808385031215615204575f80fd5b82516001600160401b038082111561521a575f80fd5b818501915085601f83011261522d575f80fd5b815161523b614acf82614a8e565b81815260059190911b83018401908481019088831115615259575f80fd5b8585015b8381101561528f57805185811115615273575f80fd5b6152818b89838a0101615102565b84525091860191860161525d565b5098975050505050505050565b604081525f6152ae6040830185614847565b82810360208401526134f78185614847565b634e487b7160e01b5f52601160045260245ffd5b5f600182016152e5576152e56152c0565b5060010190565b818103818111156105df576105df6152c0565b5f8060408385031215615310575f80fd5b8251915061532060208401614e69565b90509250929050565b808201808211156105df576105df6152c0565b600181811c9082168061535057607f821691505b60208210810361536e57634e487b7160e01b5f52602260045260245ffd5b50919050565b5f81546153808161533c565b80855260206001838116801561539d57600181146153b7576153e2565b60ff1985168884015283151560051b8801830195506153e2565b865f52825f205f5b858110156153da5781548a82018601529083019084016153bf565b890184019650505b505050505092915050565b6001600160a01b0386811682528516602082015260a0604082018190525f9061541890830186615374565b828103606084015261542a818661492e565b90508281036080840152613fc18185614971565b5f6020828403121561544e575f80fd5b81516001600160401b03811115615463575f80fd5b61286984828501615041565b8681526001600160a01b038616602082015260c0604082018190525f906154989083018761492e565b82810360608401526154aa8187614971565b6080840195909552505060a00152949350505050565b5f80604083850312156154d1575f80fd5b82516001600160401b03808211156154e7575f80fd5b6154f386838701614fdc565b93506020850151915080821115615508575f80fd5b50614d4e85828601615041565b5f60208284031215615525575f80fd5b81516001600160401b0381111561553a575f80fd5b61286984828501615102565b5f6020808385031215615557575f80fd5b82516001600160401b038082111561556d575f80fd5b818501915085601f830112615580575f80fd5b815161558e614acf82614a8e565b81815260059190911b830184019084810190888311156155ac575f80fd5b8585015b8381101561528f578051858111156155c6575f80fd5b6155d48b89838a0101614eb7565b8452509186019186016155b0565b5f8282518085526020808601955060208260051b840101602086015f5b8481101561492157601f1986840301895261561b838351614847565b988401989250908301906001016155ff565b604081525f61563f60408301846155e2565b82810360208401526002815261016160f51b60208201526040810191505092915050565b5f60208284031215615673575f80fd5b81516001600160401b03811115615688575f80fd5b61286984828501614fdc565b604081525f6156a660408301846155e2565b828103602084015260018152602d60f81b60208201526040810191505092915050565b64022b0b937160dd1b81525f84516156e8816005850160208901614825565b7f20616e642066656573206f6e20537761705820706f6f6c200000000000000000600591840191820152845161572581601d840160208901614825565b68010313c9024b1b434960bd1b601d9290910191820152835161574f816026840160208801614825565b0160260195945050505050565b8481525f60018060a01b03808616602084015260806040840152845160a0608085015261578d610120850182614847565b90508160208701511660a08501528160408701511660c08501528160608701511660e0850152816080870151166101008501528381036060850152613fc18186614847565b5f80604083850312156157e3575f80fd5b82516001600160401b038111156157f8575f80fd5b61580485828601614fdc565b925050602083015190509250929050565b848152608060208201525f61582d6080830186615374565b6001600160a01b03949094166040830152506060015292915050565b6001600160a01b038581168252841660208201526080604082018190525f906158749083018561492e565b82810360608401526158868185614971565b979650505050505050565b6001600160a01b03888116825287811660208301528681166040830152606082018690528416608082015260e060a082018190525f906158d39083018561492e565b82810360c08401526158e58185614971565b9a9950505050505050505050565b604081525f615905604083018561492e565b82810360208401526134f7818561492e565b5f8060408385031215615928575f80fd5b505080516020909101519092909150565b80820281158282048414176105df576105df6152c0565b5f8261596a57634e487b7160e01b5f52601260045260245ffd5b500490565b606081525f615981606083018661492e565b8281036020840152615993818661492e565b905082810360408401526140f08185614971565b601f82111561143657805f5260205f20601f840160051c810160208510156159cc5750805b601f840160051c820191505b818110156159eb575f81556001016159d8565b5050505050565b81516001600160401b03811115615a0b57615a0b614a22565b615a1f81615a19845461533c565b846159a7565b602080601f831160018114615a52575f8415615a3b5750858301515b5f19600386901b1c1916600185901b1785556121f5565b5f85815260208120601f198616915b82811015615a8057888601518255948401946001909101908401615a61565b5085821015615a9d57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f8251615abe818460208701614825565b9190910192915050565b6001600160a01b03868116825285811660208301528416604082015260a0606082018190525f90615afb9083018561492e565b90508260808301529695505050505050565b5f60208284031215615b1d575f80fd5b815163ffffffff81168114611453575f80fd5b5f60208284031215615b40575f80fd5b815161145381614b81565b805161ffff81168114611929575f80fd5b5f805f805f8060c08789031215615b71575f80fd5b8651615b7c816148a7565b6020880151909650615b8d81614b81565b9450615b9b60408801615b4b565b9350606087015160ff81168114615bb0575f80fd5b9250615bbe60808801615b4b565b9150615bcc60a08801614e69565b9050929550929550929556fea6fdc931ca23c69f54119a0a2d6478619b5aa365084590a1fbc287668fbabe00e61f0a7b2953b9e28e48cc07562ad7979478dcaee972e68dcf3b10da2cba6000a2646970667358221220dfdb8d8f19ff02d80c686da25c0898194702e610f7c02b1f98a4981407dab07864736f6c63430008170033
Deployed Bytecode
0x608060405234801561000f575f80fd5b5060043610610281575f3560e01c80636f307dc311610156578063aa47f4e1116100ca578063f2c33e2d11610084578063f2c33e2d14610579578063f815c4ff1461059d578063f985b0bc146105a5578063fbfa77cf146105b8578063fdff667c146105c0578063ffa1ad7414610499575f80fd5b8063aa47f4e11461051a578063aefb075114610522578063b600585a14610545578063b6c8cdef14610558578063b9f5be411461055e578063f1faf05014610571575f80fd5b80638a7f53601161011b5780638a7f536014610491578063936725ec146104995780639736374e146104bd57806399f428cf146104c45780639b3ff191146104d7578063a2b7722c14610507575f80fd5b80636f307dc31461045c57806371a97305146104645780637284e4161461047957806374bac4291461048157806380e7ac7c14610489575f80fd5b806341affeb8116101f857806350f4e419116101b257806350f4e419146103df57806359498ab7146103ff5780635b0f088a1461040757806367cf905a1461042b57806367fde573146104335780636d9894391461043b575f80fd5b806341affeb8146103835780634593144c146103965780634875c9681461039e57806348d7d9eb146103a65780634bde38c8146103cf5780634fa5d854146103d7575f80fd5b80631ec71e05116102495780631ec71e05146102f3578063278de000146103095780632a8ba2931461031d5780632d433b281461034e5780632ddbd13a14610371578063394f523214610379575f80fd5b806301ffc9a7146102855780630c56ae3b146102ad57806313e63180146102cd57806316f0115b146102e3578063190024e0146102eb575b5f80fd5b6102986102933660046147fe565b6105d5565b60405190151581526020015b60405180910390f35b6102b56105e5565b6040516001600160a01b0390911681526020016102a4565b6102d5610616565b6040519081526020016102a4565b6102b5610628565b6102d5610647565b6102fb6106e9565b6040516102a4929190614872565b5f80516020615bf9833981519152546102d5565b610341604051806040016040528060058152602001640312e322e360dc1b81525081565b6040516102a49190614895565b61036161035c3660046148bb565b6108b3565b6040516102a494939291906149a0565b6102d5610cac565b610381610cbe565b005b610381610391366004614b8f565b610d51565b6102d56110f3565b610341611126565b6103c1604080515f8082526020820190815281830190925291565b6040516102a4929190614c6d565b6102b561114f565b61038161117e565b6103f26103ed366004614c91565b61143b565b6040516102a49190614ce7565b6103c161145a565b610341604051806040016040528060058152602001640322e302e360dc1b81525081565b6103f26114ec565b6103816115d7565b61044e610449366004614cf9565b6115f3565b6040516102a4929190614d58565b6102b56116f8565b61046c611713565b6040516102a49190614d79565b61034161177c565b610298611899565b6102986118a9565b6103416118bb565b610341604051806040016040528060058152602001640312e302e360dc1b81525081565b6001610298565b6103816104d2366004614d8b565b6118de565b7fa6fdc931ca23c69f54119a0a2d6478619b5aa365084590a1fbc287668fbabe01546001600160a01b03166102b5565b6102d5610515366004614db9565b6118f4565b61046c61192e565b604080518082019091526007815266436c617373696360c81b6020820152610341565b61044e610553366004614cf9565b61199b565b5f610298565b6103f261056c366004614dea565b611a8d565b6102d5611aa0565b610341604051806040016040528060058152602001640c4b8c0b8d60da1b81525081565b6102d5611ab2565b6103f26105b3366004614e01565b611ac4565b6102b5611b6d565b6105c8611b76565b6040516102a49190614e2c565b5f6105df82611be8565b92915050565b5f806105ef611c0c565b9050806080015160018151811061060857610608614e3e565b602002602001015191505090565b5f61061f611c33565b60020154905090565b5f5f80516020615bd98339815191525b546001600160a01b0316919050565b6040805162965fff60e81b60208201525f6023820181905282516006818403018152602683019384905263bfe370d960e01b90935291734f76add676c04eca837130ceb58bc173de8799de9163bfe370d9916106a591602a01614895565b602060405180830381865af41580156106c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106e49190614e52565b905090565b60605f806106f5611c0c565b90505f81608001515f8151811061070e5761070e614e3e565b602002602001015190505f816001600160a01b0316637f7a1eec6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610755573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107799190614e78565b6107e257816001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107b9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107dd9190614e9c565b610842565b816001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa15801561081e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108429190614e9c565b90505f816001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015610880573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526108a79190810190614f17565b965f9650945050505050565b6060806060805f856001600160a01b0316634254af1c6108d16118bb565b805190602001206040518263ffffffff1660e01b81526004016108f691815260200190565b5f60405180830381865afa158015610910573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526109379190810190614f48565b602090810151604080515f80825281850181815282840180855263c45a015560e01b90529251919850919550919350916001600160a01b0389169163c45a0155916044808a019290818b030181865afa158015610996573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109ba9190614e9c565b6001600160a01b031663871fd6826040518163ffffffff1660e01b81526004015f60405180830381865afa1580156109f4573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610a1b91908101906151f3565b80519091505f805b82811015610af2575f848281518110610a3e57610a3e614e3e565b60200260200101519050805f01515f148015610ad85750734f76add676c04eca837130ceb58bc173de8799de6321a496428260400151610a7c611126565b6040518363ffffffff1660e01b8152600401610a9992919061529c565b602060405180830381865af4158015610ab4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ad89190614e78565b15610ae957610ae6836152d4565b92505b50600101610a23565b50806001600160401b03811115610b0b57610b0b614a22565b604051908082528060200260200182016040528015610b3e57816020015b6060815260200190600190039081610b295790505b509750806001600160401b03811115610b5957610b59614a22565b604051908082528060200260200182016040528015610b82578160200160208202803683370190505b5095505f90505f5b82811015610ca0575f848281518110610ba557610ba5614e3e565b60200260200101519050805f01515f148015610c3f5750734f76add676c04eca837130ceb58bc173de8799de6321a496428260400151610be3611126565b6040518363ffffffff1660e01b8152600401610c0092919061529c565b602060405180830381865af4158015610c1b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c3f9190614e78565b15610c975781888481518110610c5757610c57614e3e565b602002602001018181525050610c6d8187611c57565b8a8481518110610c7f57610c7f614e3e565b602002602001018190525082610c94906152d4565b92505b50600101610b8a565b50505050509193509193565b5f610cb5611c33565b60010154905090565b610cc6611f42565b73e347a67358dd7cba1eb146b9a60172a10cb8abee63fede401f5f80516020615bf9833981519152610cf661114f565b6040516001600160e01b031960e085901b16815260048101929092526001600160a01b031660248201526044015f6040518083038186803b158015610d39575f80fd5b505af4158015610d4b573d5f803e3d5ffd5b50505050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff1615906001600160401b03165f81158015610d955750825b90505f826001600160401b03166001148015610db05750303b155b905081158015610dbe575080155b15610ddc5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610e0657845460ff60401b1916600160401b1785555b87516002141580610e1957508651600114155b80610e245750855115155b15610e42576040516363cf6b6160e01b815260040160405180910390fd5b5f610e7f895f81518110610e5857610e58614e3e565b6020026020010151895f81518110610e7257610e72614e3e565b6020026020010151611fd1565b90508060800151516002141580610e9a575060a08101515115155b80610ea9575060c08101515115155b15610ec7576040516325b769d160e11b815260040160405180910390fd5b610f956040518060a001604052806040518060400160405280600f81526020016e49636869205377617058204661726d60881b81525081526020018b5f81518110610f1457610f14614e3e565b60200260200101516001600160a01b031681526020018b600181518110610f3d57610f3d614e3e565b60200260200101516001600160a01b0316815260200183602001516001600160a01b0316815260200183608001515f81518110610f7c57610f7c614e3e565b60200260200101516001600160a01b03168152506120a7565b610fd1895f81518110610faa57610faa614e3e565b6020026020010151895f81518110610fc457610fc4614e3e565b6020026020010151612171565b5f610fda611713565b905061103182608001515f81518110610ff557610ff5614e3e565b60200260200101515f19835f8151811061101157611011614e3e565b60200260200101516001600160a01b03166121fd9092919063ffffffff16565b61106782608001515f8151811061104a5761104a614e3e565b60200260200101515f198360018151811061101157611011614e3e565b6110a1826080015160018151811061108157611081614e3e565b60200260200101515f1984608001515f8151811061101157611011614e3e565b505083156110e957845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050565b5f6106e461112260017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f16152ec565b5490565b60408051808201909152600f81526e49636869205377617058204661726d60881b602082015290565b5f6106e461112260017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d66152ec565b6111866122ba565b61118e6122eb565b5f611197611c33565b805460408051637299470360e11b815281519394506001600160a01b03909216925f92849263e5328e06926004808401938290030181865afa1580156111df573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061120391906152ff565b5090508015611436575f61121561114f565b60088501549091505f808080611229612368565b93509350935093505f6112395f90565b61133d5761126185878151811061125257611252614e3e565b6020026020010151848461271f565b84878151811061127357611273614e3e565b602002602001018181516112879190615329565b915081815250505f73e347a67358dd7cba1eb146b9a60172a10cb8abee6356cd528e898c8e6007018a8a6040518663ffffffff1660e01b81526004016112d19594939291906153ed565b5f60405180830381865af41580156112eb573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611312919081019061543e565b90505f61131f87836127a3565b90508b600101549250801561133657611336612871565b50506113c1565b6040516336ac731760e11b81526001600160a01b038a1690636d58e62e9061136b9088908890600401614c6d565b5f604051808303815f87803b158015611382575f80fd5b505af1158015611394573d5f803e3d5ffd5b505050506113ad855f8151811061125257611252614e3e565b506113b885856127a3565b506113c1612871565b60405163640f244560e01b815273e347a67358dd7cba1eb146b9a60172a10cb8abee9063640f244590611402908d908b908a908a908f90899060040161546f565b5f6040518083038186803b158015611418575f80fd5b505af415801561142a573d5f803e3d5ffd5b50505050505050505050505b505050565b60606114456122ba565b61145084848461290a565b90505b9392505050565b606080611465612982565b604051633f8b51a560e21b8152919350915073e347a67358dd7cba1eb146b9a60172a10cb8abee9063fe2d4694906114a39085908590600401614c6d565b5f60405180830381865af41580156114bd573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526114e491908101906154c0565b915091509091565b60605f6114f7611c33565b60068101546040805160028082526060820183529394506001600160a01b039092169290602083019080368337019050509250806001600160a01b0316637f7a1eec6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611566573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061158a9190614e78565b156115bb57670de0b6b3a7640000835f815181106115aa576115aa614e3e565b602002602001018181525050505090565b670de0b6b3a7640000836001815181106115aa576115aa614e3e565b6115df612b57565b6115f06115ea610cac565b30612c72565b50565b60605f8351600114801561163f575061160a611c33565b6006015484516001600160a01b039091169085905f9061162c5761162c614e3e565b60200260200101516001600160a01b0316145b801561167657505f6001600160a01b0316845f8151811061166257611662614e3e565b60200260200101516001600160a01b031614155b156116e257825160011461169d57604051630ef9926760e21b815260040160405180910390fd5b825f815181106116af576116af614e3e565b602002602001015190506116db835f815181106116ce576116ce614e3e565b6020026020010151612e2f565b91506116f1565b6116ec8484612e3a565b915091505b9250929050565b5f611701611c33565b600601546001600160a01b0316919050565b606061171d611c33565b60050180548060200260200160405190810160405280929190818152602001828054801561177257602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311611754575b5050505050905090565b60605f80516020615bf98339815191525f80516020615bd98339815191525f6117a361114f565b6001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117de573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118029190614e9c565b835460405163538a85a160e01b81526001600160a01b03929092169163538a85a1916118349160040190815260200190565b5f60405180830381865afa15801561184e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526118759190810190615515565b60018301549091506118919082906001600160a01b0316611c57565b935050505090565b5f6118a2610cac565b1515919050565b5f806118b3611c0c565b511592915050565b604080518082019091526009815268105b19d9589c98558d60ba1b602082015290565b6118e66122ba565b6118f08282612e47565b5050565b5f6118fd6122ba565b5f611906611c33565b905080600201545f0361191a574260028201555b611925836001612f2f565b9150505b919050565b60605f80516020615bf983398151915260010180548060200260200160405190810160405280929190818152602001828054801561177257602002820191905f5260205f209081546001600160a01b03168152600190910190602001808311611754575050505050905090565b60605f835160011480156119e757506119b2611c33565b6006015484516001600160a01b039091169085905f906119d4576119d4614e3e565b60200260200101516001600160a01b0316145b8015611a1e57505f6001600160a01b0316845f81518110611a0a57611a0a614e3e565b60200260200101516001600160a01b031614155b15611a83578251600114611a4557604051630ef9926760e21b815260040160405180910390fd5b825f81518110611a5757611a57614e3e565b602002602001015190506116db835f81518110611a7657611a76614e3e565b60200260200101516130a2565b6116ec8484613218565b6060611a976122ba565b6105df82613292565b5f611aa9611c33565b60040154905090565b5f611abb611c33565b60030154905090565b6060611ace6122ba565b73e347a67358dd7cba1eb146b9a60172a10cb8abee6325567aef611af0611c33565b6040516001600160e01b031960e084901b168152600481019190915260248101879052604481018690526001600160a01b03851660648201526084015f60405180830381865af4158015611b46573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611450919081019061543e565b5f610638611c33565b604080516001808252818301909252606091816020015b6060815260200190600190039081611b8d5790505090506040518060400160405280600b81526020016a436f6d706f756e64696e6760a81b815250815f81518110611bda57611bda614e3e565b602002602001018190525090565b5f6001600160e01b031982166396cf43c560e01b14806105df57506105df8261334e565b611c1461474c565b6106e4611c1f61114f565b5f80516020615bf983398151915254611fd1565b7fb14b643f49bed6a2c6693bbd50f68dc950245db265c66acadbfa51ccc8c3ba0090565b6060734f76add676c04eca837130ceb58bc173de8799de631dfab928734f76add676c04eca837130ceb58bc173de8799de63fbcadbe986606001516040518263ffffffff1660e01b8152600401611cae9190614d79565b5f60405180830381865af4158015611cc8573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611cef9190810190615546565b6040518263ffffffff1660e01b8152600401611d0b919061562d565b5f60405180830381865af4158015611d25573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611d4c9190810190614f17565b602084015160405163a912616960e01b81526001600160a01b039182166004820152734f76add676c04eca837130ceb58bc173de8799de91631dfab92891839163fbcadbe9919088169063a9126169906024015f60405180830381865afa158015611db9573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611de09190810190615663565b6040518263ffffffff1660e01b8152600401611dfc9190614d79565b5f60405180830381865af4158015611e16573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611e3d9190810190615546565b6040518263ffffffff1660e01b8152600401611e599190615694565b5f60405180830381865af4158015611e73573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611e9a9190810190614f17565b84608001515f81518110611eb057611eb0614e3e565b60200260200101516001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015611ef2573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611f199190810190614f17565b604051602001611f2b939291906156c9565b604051602081830303815290604052905092915050565b611f4a61114f565b6040516336b87bd760e11b81523360048201526001600160a01b039190911690636d70f7ae90602401602060405180830381865afa158015611f8e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fb29190614e78565b611fcf57604051631f0853c160e21b815260040160405180910390fd5b565b611fd961474c565b826001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015612015573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120399190614e9c565b6001600160a01b031663538a85a1836040518263ffffffff1660e01b815260040161206691815260200190565b5f60405180830381865afa158015612080573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526114539190810190615515565b6120af613372565b5f5f80516020615bd9833981519152905060605f73f732df3f82d1ce0234bf5ee6933fd370b8b30f2a638ff2a774848660200151876120ec6118bb565b6040518563ffffffff1660e01b815260040161210b949392919061575c565b5f60405180830381865af4158015612125573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261214c91908101906157d2565b8092508193505050610d4b8460200151855f01518660400151858860800151866133bb565b612179613372565b73e347a67358dd7cba1eb146b9a60172a10cb8abee634ab3b02f5f80516020615bf98339815191526121a9611c33565b60070185856040518563ffffffff1660e01b81526004016121cd9493929190615815565b5f6040518083038186803b1580156121e3575f80fd5b505af41580156121f5573d5f803e3d5ffd5b505050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261224e848261345f565b610d4b576040516001600160a01b0384811660248301525f60448301526122b091869182169063095ea7b3906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050613500565b610d4b8482613500565b6122c2611c33565b546001600160a01b03163314611fcf576040516362df054560e01b815260040160405180910390fd5b306001600160a01b03166374bac4296040518163ffffffff1660e01b8152600401602060405180830381865afa158015612327573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061234b9190614e78565b611fcf576040516309ea311f60e11b815260040160405180910390fd5b606080606080612376611713565b935083516001600160401b0381111561239157612391614a22565b6040519080825280602002602001820160405280156123ba578160200160208202803683370190505b507fe61f0a7b2953b9e28e48cc07562ad7979478dcaee972e68dcf3b10da2cba60018054604080516020808402820181019092528281529396505f80516020615bf98339815191529392919083018282801561243d57602002820191905f5260205f20905b81546001600160a01b0316815260019091019060200180831161241f575b505050505092505f73e347a67358dd7cba1eb146b9a60172a10cb8abee63e3d670d7855f8151811061247157612471614e3e565b60200260200101516040518263ffffffff1660e01b81526004016124a491906001600160a01b0391909116815260200190565b602060405180830381865af41580156124bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124e39190614e52565b604080516001808252818301909252919250602080830190803683370190505092505f61250e611c0c565b90505f816080015160018151811061252857612528614e3e565b60200260200101516001600160a01b0316637c91e4eb6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561256b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061258f9190614e9c565b6040805160018082528183019092529192505f91906020808301908036833701905050905082608001516001815181106125cb576125cb614e3e565b6020026020010151815f815181106125e5576125e5614e3e565b6001600160a01b03928316602091820292909201015260405163f9f031df60e01b81529083169063f9f031df90612620908490600401614d79565b5f604051808303815f87803b158015612637575f80fd5b505af1158015612649573d5f803e3d5ffd5b505050508373e347a67358dd7cba1eb146b9a60172a10cb8abee63e3d670d7895f8151811061267a5761267a614e3e565b60200260200101516040518263ffffffff1660e01b81526004016126ad91906001600160a01b0391909116815260200190565b602060405180830381865af41580156126c8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126ec9190614e52565b6126f691906152ec565b865f8151811061270857612708614e3e565b602002602001018181525050505050505090919293565b5f73e347a67358dd7cba1eb146b9a60172a10cb8abee6374e714c861274261114f565b8686866040518563ffffffff1660e01b81526004016127649493929190615849565b602060405180830381865af415801561277f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114509190614e52565b5f5f80516020615bd983398151915273f732df3f82d1ce0234bf5ee6933fd370b8b30f2a6372d46b086127d461114f565b6127dc611b6d565b60018501546001600160a01b03166127f2611c33565b6008015486546040516001600160e01b031960e088901b16815261282a95949392916001600160a01b0316908c908c90600401615891565b602060405180830381865af4158015612845573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128699190614e78565b949350505050565b5f61287a6114ec565b90505f61289f825f8151811061289257612892614e3e565b6020026020010151613566565b90506001815f815181106128b5576128b5614e3e565b602002602001015111806128e357506001816001815181106128d9576128d9614e3e565b6020026020010151115b156118f0575f6128f282613616565b9092509050600a81111561143657610d4b825f612f2f565b606073f732df3f82d1ce0234bf5ee6933fd370b8b30f2a639dfc419f8561292f611713565b6040518363ffffffff1660e01b815260040161294c9291906158f3565b5f6040518083038186803b158015612962575f80fd5b505af4158015612974573d5f803e3d5ffd5b505050506114508383612c72565b6060805f61298e611c33565b600581018054604080516020808402820181019092528281529394508301828280156129e157602002820191905f5260205f20905b81546001600160a01b031681526001909101906020018083116129c3575b505050506001830154600684015460408051636253bb0f60e11b8152815195985092946001600160a01b0390921693505f928392859263c4a7761e92600480820193918290030181865afa158015612a3b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a5f9190615917565b915091505f836001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612aa0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ac49190614e52565b604080516002808252606082018352929350919060208301908036833701905050965080612af28685615939565b612afc9190615950565b875f81518110612b0e57612b0e614e3e565b602090810291909101015280612b248684615939565b612b2e9190615950565b87600181518110612b4157612b41614e3e565b6020026020010181815250505050505050509091565b5f612b6061114f565b9050336001600160a01b0316816001600160a01b0316635aa6e6756040518163ffffffff1660e01b8152600401602060405180830381865afa158015612ba8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bcc9190614e9c565b6001600160a01b031614158015612c545750336001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c24573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c489190614e9c565b6001600160a01b031614155b156115f0576040516354299b6f60e01b815260040160405180910390fd5b60605f612c7d611c0c565b90508060800151600181518110612c9657612c96614e3e565b60200260200101516001600160a01b0316632e1a7d4d856040518263ffffffff1660e01b8152600401612ccb91815260200190565b5f604051808303815f87803b158015612ce2575f80fd5b505af1158015612cf4573d5f803e3d5ffd5b5060029250612d01915050565b604051908082528060200260200182016040528015612d2a578160200160208202803683370190505b50915080608001515f81518110612d4357612d43614e3e565b60200260200101516001600160a01b031662f714ce85856040518363ffffffff1660e01b8152600401612d899291909182526001600160a01b0316602082015260400190565b60408051808303815f875af1158015612da4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612dc89190615917565b835f81518110612dda57612dda614e3e565b6020026020010184600181518110612df457612df4614e3e565b6020908102919091010191909152525f612e0c611c33565b905084816001015f828254612e2191906152ec565b909155509295945050505050565b60606105df826130a2565b60605f6116ec8484613218565b5f612e50611c0c565b90508060800151600181518110612e6957612e69614e3e565b60200260200101516001600160a01b0316632e1a7d4d846040518263ffffffff1660e01b8152600401612e9e91815260200190565b5f604051808303815f87803b158015612eb5575f80fd5b505af1158015612ec7573d5f803e3d5ffd5b50505050612f06828483608001515f81518110612ee657612ee6614e3e565b60200260200101516001600160a01b0316613d409092919063ffffffff16565b5f612f0f611c33565b905083816001015f828254612f2491906152ec565b909155505050505050565b5f80612f39611c0c565b905080608001515f81518110612f5157612f51614e3e565b60200260200101516001600160a01b0316638dbdbe6d855f81518110612f7957612f79614e3e565b602002602001015186600181518110612f9457612f94614e3e565b60209081029190910101516040516001600160e01b031960e085901b168152600481019290925260248201523060448201526064016020604051808303815f875af1158015612fe5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130099190614e52565b9150806080015160018151811061302257613022614e3e565b60200260200101516001600160a01b031663b6b55f25836040518263ffffffff1660e01b815260040161305791815260200190565b5f604051808303815f87803b15801561306e575f80fd5b505af1158015613080573d5f803e3d5ffd5b505050505f61308d611c33565b905082816001015f828254612e219190615329565b60605f6130ad611c33565b600681015460408051636253bb0f60e11b815281519394506001600160a01b03909216925f928392859263c4a7761e9260048082019392918290030181865afa1580156130fc573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131209190615917565b915091505f836001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613161573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131859190614e52565b6040805160028082526060820183529293509190602083019080368337019050509550806131b38885615939565b6131bd9190615950565b865f815181106131cf576131cf614e3e565b6020908102919091010152806131e58884615939565b6131ef9190615950565b8660018151811061320257613202614e3e565b6020026020010181815250505050505050919050565b60605f73f732df3f82d1ce0234bf5ee6933fd370b8b30f2a639d186c788561323e611713565b866040518463ffffffff1660e01b815260040161325d9392919061596f565b5f6040518083038186803b158015613273575f80fd5b505af4158015613285573d5f803e3d5ffd5b505050506116ec83613616565b60605f61329d611c0c565b905080608001516001815181106132b6576132b6614e3e565b60200260200101516001600160a01b031663b6b55f25846040518263ffffffff1660e01b81526004016132eb91815260200190565b5f604051808303815f87803b158015613302575f80fd5b505af1158015613314573d5f803e3d5ffd5b50505050613321836130a2565b91505f61332c611c33565b905083816001015f8282546133419190615329565b9091555092949350505050565b5f6001600160e01b031982166303d859d560e11b14806105df57506105df82613d71565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16611fcf57604051631afcd79f60e31b815260040160405180910390fd5b6133c3613372565b6133cc86613d95565b5f6133d5611c33565b600881018390556006810180546001600160a01b0319166001600160a01b03861617905584519091508690869086908690869060078701905f908890829061342690600584019060208a0190614790565b5081546001600160a01b03808a166101009390930a928302920219161790555061345086826159f2565b50505050505050505050505050565b5f805f846001600160a01b03168460405161347a9190615aad565b5f604051808303815f865af19150503d805f81146134b3576040519150601f19603f3d011682016040523d82523d5f602084013e6134b8565b606091505b50915091508180156134e25750805115806134e25750808060200190518101906134e29190614e78565b80156134f757505f856001600160a01b03163b115b95945050505050565b5f6135146001600160a01b03841683613ef0565b905080515f141580156135385750808060200190518101906135369190614e78565b155b1561143657604051635274afe760e01b81526001600160a01b03841660048201526024015b60405180910390fd5b60605f80516020615bd983398151915273f732df3f82d1ce0234bf5ee6933fd370b8b30f2a633f9406db61359861114f565b600184015484546001600160a01b0391821691166135b4611713565b886040518663ffffffff1660e01b81526004016135d5959493929190615ac8565b5f60405180830381865af41580156135ef573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611925919081019061543e565b60605f80613622611c33565b60068101546040805160028082526060820183529394506001600160a01b039092169290602083019080368337019050509350806001600160a01b0316637f7a1eec6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613691573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136b59190614e78565b156136f757845f815181106136cc576136cc614e3e565b6020026020010151845f815181106136e6576136e6614e3e565b602002602001018181525050613732565b8460018151811061370a5761370a614e3e565b60200260200101518460018151811061372557613725614e3e565b6020026020010181815250505b60408051610140810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810191909152816001600160a01b03166316f0115b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137be573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137e29190614e9c565b8160e001906001600160a01b031690816001600160a01b031681525050816001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa15801561383b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061385f9190614e9c565b8161010001906001600160a01b031690816001600160a01b031681525050816001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138b9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138dd9190614e9c565b8161012001906001600160a01b031690816001600160a01b031681525050816001600160a01b031663f62073266040518163ffffffff1660e01b8152600401602060405180830381865afa158015613937573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061395b9190615b0d565b63ffffffff16815260408051630dfe168160e01b81529051613a9d916001600160a01b03851691630dfe1681916004808201926020929091908290030181865afa1580156139ab573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139cf9190614e9c565b836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa158015613a0b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a2f9190614e9c565b846001600160a01b031663065e53606040518163ffffffff1660e01b8152600401602060405180830381865afa158015613a6b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a8f9190615b30565b670de0b6b3a7640000613efd565b604082015260e08101516101008201516101208301518351613aca93929190670de0b6b3a7640000613f12565b816060018181525050816001600160a01b03166391563d326040518163ffffffff1660e01b8152600401602060405180830381865afa158015613b0f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b339190615b0d565b63ffffffff1660208201819052613b4e578060600151613b75565b613b758160e001518261010001518361012001518460200151670de0b6b3a7640000613f12565b8160800181815250505f80836001600160a01b031663c4a7761e6040518163ffffffff1660e01b81526004016040805180830381865afa158015613bbb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613bdf9190615917565b915091505f613c018460400151856060015186608001515f8860200151613fcd565b90505f670de0b6b3a7640000828a5f81518110613c2057613c20614e3e565b6020026020010151613c329190615939565b613c3c9190615950565b90508089600181518110613c5257613c52614e3e565b6020026020010151613c649190615329565b97505f866001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613ca3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613cc79190614e52565b90508015613d33575f613cee87604001518860600151896080015160018b60200151613fcd565b90505f670de0b6b3a7640000613d048389615939565b613d0e9190615950565b9050613d1a8682615329565b613d24848d615939565b613d2e9190615950565b9a5050505b5050505050505050915091565b6040516001600160a01b0383811660248301526044820183905261143691859182169063a9059cbb9060640161227e565b5f6001600160e01b031982166342c352d360e11b14806105df57506105df8261402d565b613d9d613372565b6001600160a01b0381161580613e2357505f6001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613df4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613e189190614e9c565b6001600160a01b0316145b15613e41576040516371c42ac360e01b815260040160405180910390fd5b613e74613e6f60017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d66152ec565b829055565b613ea643613ea360017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f16152ec565b55565b604080516001600160a01b0383168152426020820152438183015290517f1a2dd071001ebf6e03174e3df5b305795a4ad5d41d8fdb9ba41dbbe2367134269181900360600190a150565b606061145383835f614061565b5f6134f783613f0b846140fa565b8787614131565b5f80613f1d876144e5565b604051638241348960e01b81526001600160a01b038216600482015263ffffffff861660248201529091505f9073e3c14573ccd72f95a739f297dcfa8d525aa330ac90638241348990604401602060405180830381865af4158015613f84573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613fa89190615b30565b60020b9050613fc181613fba866140fa565b8989614131565b98975050505050505050565b5f82156140045763ffffffff821615613ffa57613ff3613fed8787614597565b85614597565b90506134f7565b613ff38686614597565b63ffffffff82161561402357613ff361401d87876145ac565b856145ac565b613ff386866145ac565b5f6001600160e01b03198216630f1ec81f60e41b14806105df57506301ffc9a760e01b6001600160e01b03198316146105df565b6060814710156140865760405163cd78605960e01b815230600482015260240161355d565b5f80856001600160a01b031684866040516140a19190615aad565b5f6040518083038185875af1925050503d805f81146140db576040519150601f19603f3d011682016040523d82523d5f602084013e6140e0565b606091505b50915091506140f08683836145ba565b9695505050505050565b5f6001600160801b0382111561412d576040516306dfcc6560e41b8152608060048201526024810183905260440161355d565b5090565b60405163986cfba360e01b8152600285900b60048201525f90819073bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063986cfba390602401602060405180830381865af4158015614186573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906141aa9190614e9c565b90506001600160801b036001600160a01b03821611614315575f6141d76001600160a01b03831680615939565b9050836001600160a01b0316856001600160a01b0316106142825760405163554d048960e11b8152600160c01b60048201526001600160801b03871660248201526044810182905273bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af4158015614259573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061427d9190614e52565b61430d565b60405163554d048960e11b8152600481018290526001600160801b0387166024820152600160c01b604482015273bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af41580156142e9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061430d9190614e52565b9250506144dc565b60405163554d048960e11b81526001600160a01b038216600482018190526024820152600160401b60448201525f9073bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af415801561437e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143a29190614e52565b9050836001600160a01b0316856001600160a01b03161061444d5760405163554d048960e11b8152600160801b60048201526001600160801b03871660248201526044810182905273bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af4158015614424573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906144489190614e52565b6144d8565b60405163554d048960e11b8152600481018290526001600160801b0387166024820152600160801b604482015273bbc63ee4a06bf1f2432ccc4d70103e3d465fca399063aa9a091290606401602060405180830381865af41580156144b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906144d89190614e52565b9250505b50949350505050565b5f816001600160a01b031663ef01df4f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015614522573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906145469190614e9c565b90506145528183614616565b6119295760405162461bcd60e51b815260206004820152601660248201527524ab1d103234b1b7b73732b1ba32b21038363ab3b4b760511b604482015260640161355d565b5f8183116145a55781611453565b5090919050565b5f8183106145a55781611453565b6060826145cf576145ca82614723565b611453565b81511580156145e657506001600160a01b0384163b155b1561460f57604051639996b31560e01b81526001600160a01b038516600482015260240161355d565b5080611453565b5f6001600160a01b03831661462c57505f6105df565b5f829050806001600160a01b031663ef01df4f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561466c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906146909190614e9c565b6001600160a01b0316846001600160a01b03160361471c575f816001600160a01b031663e76c01e46040518163ffffffff1660e01b815260040160c060405180830381865afa1580156146e5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906147099190615b5c565b505093505050506134f781600116151590565b5092915050565b8051156147335780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b6040518060e001604052805f81526020015f6001600160a01b0316815260200160608152602001606081526020016060815260200160608152602001606081525090565b828054828255905f5260205f209081019282156147e3579160200282015b828111156147e357825182546001600160a01b0319166001600160a01b039091161782556020909201916001909101906147ae565b5061412d9291505b8082111561412d575f81556001016147eb565b5f6020828403121561480e575f80fd5b81356001600160e01b031981168114611453575f80fd5b5f5b8381101561483f578181015183820152602001614827565b50505f910152565b5f815180845261485e816020860160208601614825565b601f01601f19169290920160200192915050565b604081525f6148846040830185614847565b905082151560208301529392505050565b602081525f6114536020830184614847565b6001600160a01b03811681146115f0575f80fd5b5f602082840312156148cb575f80fd5b8135611453816148a7565b5f8282518085526020808601955060208260051b840101602086015f5b8481101561492157601f1986840301895261490f838351614847565b988401989250908301906001016148f3565b5090979650505050505050565b5f815180845260208085019450602084015f5b838110156149665781516001600160a01b031687529582019590820190600101614941565b509495945050505050565b5f815180845260208085019450602084015f5b8381101561496657815187529582019590820190600101614984565b608081525f6149b260808301876148d6565b602083820360208501526149c6828861492e565b915083820360408501526149da8287614971565b8481036060860152855180825260208088019450909101905f5b81811015614a1357845160020b835293830193918301916001016149f4565b50909998505050505050505050565b634e487b7160e01b5f52604160045260245ffd5b60405160e081016001600160401b0381118282101715614a5857614a58614a22565b60405290565b604051601f8201601f191681016001600160401b0381118282101715614a8657614a86614a22565b604052919050565b5f6001600160401b03821115614aa657614aa6614a22565b5060051b60200190565b5f82601f830112614abf575f80fd5b81356020614ad4614acf83614a8e565b614a5e565b8083825260208201915060208460051b870101935086841115614af5575f80fd5b602086015b84811015614b1a578035614b0d816148a7565b8352918301918301614afa565b509695505050505050565b5f82601f830112614b34575f80fd5b81356020614b44614acf83614a8e565b8083825260208201915060208460051b870101935086841115614b65575f80fd5b602086015b84811015614b1a5780358352918301918301614b6a565b8060020b81146115f0575f80fd5b5f805f60608486031215614ba1575f80fd5b83356001600160401b0380821115614bb7575f80fd5b614bc387838801614ab0565b9450602091508186013581811115614bd9575f80fd5b614be588828901614b25565b945050604086013581811115614bf9575f80fd5b86019050601f81018713614c0b575f80fd5b8035614c19614acf82614a8e565b81815260059190911b82018301908381019089831115614c37575f80fd5b928401925b82841015614c5e578335614c4f81614b81565b82529284019290840190614c3c565b80955050505050509250925092565b604081525f614c7f604083018561492e565b82810360208401526134f78185614971565b5f805f60608486031215614ca3575f80fd5b83356001600160401b03811115614cb8575f80fd5b614cc486828701614ab0565b935050602084013591506040840135614cdc816148a7565b809150509250925092565b602081525f6114536020830184614971565b5f8060408385031215614d0a575f80fd5b82356001600160401b0380821115614d20575f80fd5b614d2c86838701614ab0565b93506020850135915080821115614d41575f80fd5b50614d4e85828601614b25565b9150509250929050565b604081525f614d6a6040830185614971565b90508260208301529392505050565b602081525f611453602083018461492e565b5f8060408385031215614d9c575f80fd5b823591506020830135614dae816148a7565b809150509250929050565b5f60208284031215614dc9575f80fd5b81356001600160401b03811115614dde575f80fd5b61286984828501614b25565b5f60208284031215614dfa575f80fd5b5035919050565b5f805f60608486031215614e13575f80fd5b83359250602084013591506040840135614cdc816148a7565b602081525f61145360208301846148d6565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215614e62575f80fd5b5051919050565b80518015158114611929575f80fd5b5f60208284031215614e88575f80fd5b61145382614e69565b8051611929816148a7565b5f60208284031215614eac575f80fd5b8151611453816148a7565b5f82601f830112614ec6575f80fd5b81516001600160401b03811115614edf57614edf614a22565b614ef2601f8201601f1916602001614a5e565b818152846020838601011115614f06575f80fd5b612869826020830160208701614825565b5f60208284031215614f27575f80fd5b81516001600160401b03811115614f3c575f80fd5b61286984828501614eb7565b5f60208284031215614f58575f80fd5b81516001600160401b0380821115614f6e575f80fd5b9083019060408286031215614f81575f80fd5b604051604081018181108382111715614f9c57614f9c614a22565b604052825182811115614fad575f80fd5b614fb987828601614eb7565b82525060208301519250614fcc836148a7565b6020810192909252509392505050565b5f82601f830112614feb575f80fd5b81516020614ffb614acf83614a8e565b8083825260208201915060208460051b87010193508684111561501c575f80fd5b602086015b84811015614b1a578051615034816148a7565b8352918301918301615021565b5f82601f830112615050575f80fd5b81516020615060614acf83614a8e565b8083825260208201915060208460051b870101935086841115615081575f80fd5b602086015b84811015614b1a5780518352918301918301615086565b5f82601f8301126150ac575f80fd5b815160206150bc614acf83614a8e565b8083825260208201915060208460051b8701019350868411156150dd575f80fd5b602086015b84811015614b1a5780516150f581614b81565b83529183019183016150e2565b5f60e08284031215615112575f80fd5b61511a614a36565b90508151815261512c60208301614e91565b602082015260408201516001600160401b038082111561514a575f80fd5b61515685838601614eb7565b6040840152606084015191508082111561516e575f80fd5b61517a85838601614fdc565b60608401526080840151915080821115615192575f80fd5b61519e85838601614fdc565b608084015260a08401519150808211156151b6575f80fd5b6151c285838601615041565b60a084015260c08401519150808211156151da575f80fd5b506151e78482850161509d565b60c08301525092915050565b5f6020808385031215615204575f80fd5b82516001600160401b038082111561521a575f80fd5b818501915085601f83011261522d575f80fd5b815161523b614acf82614a8e565b81815260059190911b83018401908481019088831115615259575f80fd5b8585015b8381101561528f57805185811115615273575f80fd5b6152818b89838a0101615102565b84525091860191860161525d565b5098975050505050505050565b604081525f6152ae6040830185614847565b82810360208401526134f78185614847565b634e487b7160e01b5f52601160045260245ffd5b5f600182016152e5576152e56152c0565b5060010190565b818103818111156105df576105df6152c0565b5f8060408385031215615310575f80fd5b8251915061532060208401614e69565b90509250929050565b808201808211156105df576105df6152c0565b600181811c9082168061535057607f821691505b60208210810361536e57634e487b7160e01b5f52602260045260245ffd5b50919050565b5f81546153808161533c565b80855260206001838116801561539d57600181146153b7576153e2565b60ff1985168884015283151560051b8801830195506153e2565b865f52825f205f5b858110156153da5781548a82018601529083019084016153bf565b890184019650505b505050505092915050565b6001600160a01b0386811682528516602082015260a0604082018190525f9061541890830186615374565b828103606084015261542a818661492e565b90508281036080840152613fc18185614971565b5f6020828403121561544e575f80fd5b81516001600160401b03811115615463575f80fd5b61286984828501615041565b8681526001600160a01b038616602082015260c0604082018190525f906154989083018761492e565b82810360608401526154aa8187614971565b6080840195909552505060a00152949350505050565b5f80604083850312156154d1575f80fd5b82516001600160401b03808211156154e7575f80fd5b6154f386838701614fdc565b93506020850151915080821115615508575f80fd5b50614d4e85828601615041565b5f60208284031215615525575f80fd5b81516001600160401b0381111561553a575f80fd5b61286984828501615102565b5f6020808385031215615557575f80fd5b82516001600160401b038082111561556d575f80fd5b818501915085601f830112615580575f80fd5b815161558e614acf82614a8e565b81815260059190911b830184019084810190888311156155ac575f80fd5b8585015b8381101561528f578051858111156155c6575f80fd5b6155d48b89838a0101614eb7565b8452509186019186016155b0565b5f8282518085526020808601955060208260051b840101602086015f5b8481101561492157601f1986840301895261561b838351614847565b988401989250908301906001016155ff565b604081525f61563f60408301846155e2565b82810360208401526002815261016160f51b60208201526040810191505092915050565b5f60208284031215615673575f80fd5b81516001600160401b03811115615688575f80fd5b61286984828501614fdc565b604081525f6156a660408301846155e2565b828103602084015260018152602d60f81b60208201526040810191505092915050565b64022b0b937160dd1b81525f84516156e8816005850160208901614825565b7f20616e642066656573206f6e20537761705820706f6f6c200000000000000000600591840191820152845161572581601d840160208901614825565b68010313c9024b1b434960bd1b601d9290910191820152835161574f816026840160208801614825565b0160260195945050505050565b8481525f60018060a01b03808616602084015260806040840152845160a0608085015261578d610120850182614847565b90508160208701511660a08501528160408701511660c08501528160608701511660e0850152816080870151166101008501528381036060850152613fc18186614847565b5f80604083850312156157e3575f80fd5b82516001600160401b038111156157f8575f80fd5b61580485828601614fdc565b925050602083015190509250929050565b848152608060208201525f61582d6080830186615374565b6001600160a01b03949094166040830152506060015292915050565b6001600160a01b038581168252841660208201526080604082018190525f906158749083018561492e565b82810360608401526158868185614971565b979650505050505050565b6001600160a01b03888116825287811660208301528681166040830152606082018690528416608082015260e060a082018190525f906158d39083018561492e565b82810360c08401526158e58185614971565b9a9950505050505050505050565b604081525f615905604083018561492e565b82810360208401526134f7818561492e565b5f8060408385031215615928575f80fd5b505080516020909101519092909150565b80820281158282048414176105df576105df6152c0565b5f8261596a57634e487b7160e01b5f52601260045260245ffd5b500490565b606081525f615981606083018661492e565b8281036020840152615993818661492e565b905082810360408401526140f08185614971565b601f82111561143657805f5260205f20601f840160051c810160208510156159cc5750805b601f840160051c820191505b818110156159eb575f81556001016159d8565b5050505050565b81516001600160401b03811115615a0b57615a0b614a22565b615a1f81615a19845461533c565b846159a7565b602080601f831160018114615a52575f8415615a3b5750858301515b5f19600386901b1c1916600185901b1785556121f5565b5f85815260208120601f198616915b82811015615a8057888601518255948401946001909101908401615a61565b5085821015615a9d57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f8251615abe818460208701614825565b9190910192915050565b6001600160a01b03868116825285811660208301528416604082015260a0606082018190525f90615afb9083018561492e565b90508260808301529695505050505050565b5f60208284031215615b1d575f80fd5b815163ffffffff81168114611453575f80fd5b5f60208284031215615b40575f80fd5b815161145381614b81565b805161ffff81168114611929575f80fd5b5f805f805f8060c08789031215615b71575f80fd5b8651615b7c816148a7565b6020880151909650615b8d81614b81565b9450615b9b60408801615b4b565b9350606087015160ff81168114615bb0575f80fd5b9250615bbe60808801615b4b565b9150615bcc60a08801614e69565b9050929550929550929556fea6fdc931ca23c69f54119a0a2d6478619b5aa365084590a1fbc287668fbabe00e61f0a7b2953b9e28e48cc07562ad7979478dcaee972e68dcf3b10da2cba6000a2646970667358221220dfdb8d8f19ff02d80c686da25c0898194702e610f7c02b1f98a4981407dab07864736f6c63430008170033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.