Source Code
Overview
S Balance
S Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
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 Name:
SiloMerklFarmStrategy
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {SharedLib} from "./libs/SharedLib.sol";
import {
FarmingStrategyBase,
StrategyBase,
IFarmingStrategy,
IFactory,
StrategyLib,
IPlatform
} from "./base/FarmingStrategyBase.sol";
import {CommonLib} from "../core/libs/CommonLib.sol";
import {FarmMechanicsLib} from "./libs/FarmMechanicsLib.sol";
import {IControllable} from "../interfaces/IControllable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IPriceReader} from "../interfaces/IPriceReader.sol";
import {ISiloConfig} from "../integrations/silo/ISiloConfig.sol";
import {ISiloIncentivesController} from "../integrations/silo/ISiloIncentivesController.sol";
import {ISilo} from "../integrations/silo/ISilo.sol";
import {IStrategy} from "../interfaces/IStrategy.sol";
import {IXSilo} from "../integrations/silo/IXSilo.sol";
import {MerklStrategyBase} from "./base/MerklStrategyBase.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {StrategyIdLib} from "./libs/StrategyIdLib.sol";
import {VaultTypeLib} from "../core/libs/VaultTypeLib.sol";
/// @title Supply asset to Silo V2 and earn farm rewards from Silo and Merkl
/// Changelog:
/// 1.0.1: StrategyBase 2.6.0, fix getSpecificName, Protected collateral is not supported - #395, #394
/// @author dvpublic (https://github.com/dvpublic)
contract SiloMerklFarmStrategy is MerklStrategyBase, FarmingStrategyBase {
using SafeERC20 for IERC20;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @inheritdoc IControllable
string public constant VERSION = "1.0.1";
/// @dev Strategy logic ID used in this farm
string internal constant STRATEGY_LOGIC_ID = StrategyIdLib.SILO_MERKL_FARM;
//region ----------------------------------- Initialization
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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 != 3 || farm.nums.length != 1 || farm.ticks.length != 0) {
revert IFarmingStrategy.BadFarm();
}
address[] memory siloAssets = new address[](1);
ISilo siloVault = _getSilo(farm);
siloAssets[0] = siloVault.asset();
__StrategyBase_init(addresses[0], STRATEGY_LOGIC_ID, addresses[1], siloAssets, address(0), 0);
__FarmingStrategyBase_init(addresses[0], nums[0]);
IERC20(siloAssets[0]).forceApprove(address(siloVault), type(uint).max);
require(farm.nums[0] == 1, "Only Collateral supported, see #394");
address gauge = _getGauge(farm);
if (gauge != address(0)) {
IERC20(address(siloVault)).forceApprove(gauge, type(uint).max);
}
}
//endregion ----------------------------------- Initialization
//region ----------------------------------- View
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* VIEW FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @inheritdoc IStrategy
function strategyLogicId() public pure override returns (string memory) {
return STRATEGY_LOGIC_ID;
}
/// @inheritdoc IStrategy
function extra() external pure returns (bytes32) {
return CommonLib.bytesToBytes32(abi.encodePacked(bytes3(0x00d395), bytes3(0x000000)));
}
/// @inheritdoc IStrategy
function description() external view returns (string memory) {
IFactory.Farm memory farm = _getFarm();
return _genDesc(farm);
}
/// @inheritdoc IStrategy
function getAssetsProportions() external pure returns (uint[] memory proportions) {
proportions = new uint[](1);
proportions[0] = 1e18;
}
/// @inheritdoc IStrategy
function getRevenue() external view returns (address[] memory __assets, uint[] memory amounts) {}
/// @inheritdoc IStrategy
/// @dev returns specific value OR other name like "other asset symbol, market id"
function getSpecificName() external view override returns (string memory, bool) {
string memory specific = _getStrategyBaseStorage().specific;
if (bytes(specific).length != 0) {
return (specific, true);
}
IFactory.Farm memory farm = _getFarm();
ISilo siloVault = _getSilo(farm);
ISiloConfig config = ISiloConfig(siloVault.config());
(address silo0, address silo1) = config.getSilos();
ISilo otherSilo = ISilo(address(siloVault) == silo0 ? silo1 : silo0);
return (string.concat(IERC20Metadata(otherSilo.asset()).symbol(), ", ", CommonLib.u2s(_getMarketId())), true);
}
/// @inheritdoc IStrategy
function supportedVaultTypes() external pure override returns (string[] memory types) {
types = new string[](1);
types[0] = VaultTypeLib.COMPOUNDING;
}
/// @inheritdoc IStrategy
function initVariants(address platform_)
public
view
returns (string[] memory variants, address[] memory addresses, uint[] memory nums, int24[] memory ticks)
{
/// slither-disable-next-line ignore-unused-return
return SharedLib.initVariantsForFarm(platform_, STRATEGY_LOGIC_ID, _genDesc);
}
/// @inheritdoc IStrategy
function isHardWorkOnDepositAllowed() external pure returns (bool) {
return false;
}
/// @inheritdoc IStrategy
function isReadyForHardWork() external pure returns (bool isReady) {
isReady = true;
}
/// @inheritdoc IStrategy
function maxWithdrawAssets(uint /*mode*/ ) public view override returns (uint[] memory amounts) {
IFactory.Farm memory farm = _getFarm();
ISilo siloVault = _getSilo(farm);
amounts = new uint[](1);
amounts[0] = siloVault.maxWithdraw(address(this));
}
/// @inheritdoc IStrategy
function poolTvl() public view virtual override returns (uint tvlUsd) {
IFactory.Farm memory farm = _getFarm();
ISilo siloVault = _getSilo(farm);
address asset = siloVault.asset();
IPriceReader priceReader = IPriceReader(IPlatform(platform()).priceReader());
// get price of 1 amount of asset in USD with decimals 18
// assume that {trusted} value doesn't matter here
/// slither-disable-next-line ignore-unused-return
(uint price,) = priceReader.getPrice(asset);
return siloVault.totalAssets() * price / (10 ** IERC20Metadata(asset).decimals());
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId)
public
view
override(MerklStrategyBase, FarmingStrategyBase)
returns (bool)
{
return FarmingStrategyBase.supportsInterface(interfaceId) || MerklStrategyBase.supportsInterface(interfaceId)
|| super.supportsInterface(interfaceId);
}
//endregion ----------------------------------- View
//region ----------------------------------- Farming Strategy Base
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* FARMING STRATEGY BASE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @inheritdoc IFarmingStrategy
function farmMechanics() external pure returns (string memory) {
return FarmMechanicsLib.AUTO;
}
/// @inheritdoc IFarmingStrategy
function canFarm() external pure override returns (bool) {
return true;
}
//endregion ----------------------------------- Farming Strategy Base
//region ----------------------------------- Strategy Base
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRATEGY BASE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @inheritdoc StrategyBase
//slither-disable-next-line unused-return
function _depositAssets(uint[] memory amounts, bool /*claimRevenue*/ ) internal override returns (uint value) {
IFactory.Farm memory farm = _getFarm();
StrategyBaseStorage storage $base = _getStrategyBaseStorage();
ISilo siloVault = _getSilo(farm);
value = amounts[0];
if (value != 0) {
siloVault.deposit(value, address(this), ISilo.CollateralType.Collateral);
$base.total += value;
}
}
/// @inheritdoc StrategyBase
function _withdrawAssets(uint value, address receiver) internal override returns (uint[] memory amountsOut) {
StrategyBaseStorage storage _$_ = _getStrategyBaseStorage();
return _withdrawAssets(_$_._assets, value, receiver);
}
/// @inheritdoc StrategyBase
//slither-disable-next-line unused-return
function _withdrawAssets(
address[] memory, // _assets
uint value,
address receiver
) internal override returns (uint[] memory amountsOut) {
IFactory.Farm memory farm = _getFarm();
ISilo siloVault = _getSilo(farm);
uint toWithdraw = value;
if (address(this) == receiver) {
toWithdraw--;
}
siloVault.withdraw(toWithdraw, receiver, address(this), ISilo.CollateralType.Collateral);
amountsOut = new uint[](1);
amountsOut[0] = value;
StrategyBaseStorage storage $base = _getStrategyBaseStorage();
$base.total -= value;
}
/// @inheritdoc StrategyBase
function _liquidateRewards(
address exchangeAsset,
address[] memory rewardAssets_,
uint[] memory rewardAmounts_
) internal override(FarmingStrategyBase, StrategyBase) returns (uint earnedExchangeAsset) {
earnedExchangeAsset = FarmingStrategyBase._liquidateRewards(exchangeAsset, rewardAssets_, rewardAmounts_);
}
/// @inheritdoc StrategyBase
//slither-disable-next-line unused-return
function _claimRevenue()
internal
override
returns (
address[] memory __assets,
uint[] memory __amounts,
address[] memory __rewardAssets,
uint[] memory __rewardAmounts
)
{
StrategyBaseStorage storage $base = _getStrategyBaseStorage();
FarmingStrategyBaseStorage storage $f = _getFarmingStrategyBaseStorage();
__assets = assets();
__amounts = new uint[](__assets.length);
__rewardAssets = $f._rewardAssets;
uint lenRewards = __rewardAssets.length;
__rewardAmounts = new uint[](lenRewards);
// Merkl rewards: assume they are added on the balance automatically
// So, we don't take into accounts "balance before" - assume all balance is rewards
IFactory.Farm memory farm = _getFarm();
ISilo siloVault = _getSilo(farm);
__amounts[0] = siloVault.convertToAssets(siloVault.balanceOf(address(this))) - $base.total;
address gauge = _getGauge(farm);
if (gauge != address(0)) {
ISiloIncentivesController(gauge).claimRewards(address(this));
}
address xSilo = _getXSilo(farm);
address silo = xSilo != address(0) ? IXSilo(xSilo).asset() : address(0);
for (uint i; i < lenRewards; ++i) {
__rewardAmounts[i] = StrategyLib.balance(__rewardAssets[i]);
if (__rewardAssets[i] == silo && xSilo != address(0)) {
// xSilo => silo
uint amountXSilo = StrategyLib.balance(xSilo);
if (amountXSilo != 0) {
// instant exit with penalty 50%
__rewardAmounts[i] += IXSilo(xSilo).redeemSilo(amountXSilo, 0);
}
}
}
}
/// @inheritdoc StrategyBase
function _compound() internal override {
address[] memory _assets = assets();
uint len = _assets.length;
uint[] memory amounts = new uint[](len);
//slither-disable-next-line uninitialized-local
bool notZero;
for (uint i; i < len; ++i) {
amounts[i] = StrategyLib.balance(_assets[i]);
if (amounts[i] != 0) {
notZero = true;
}
}
IFactory.Farm memory farm = _getFarm();
ISilo siloVault = _getSilo(farm);
StrategyBaseStorage storage $base = _getStrategyBaseStorage();
$base.total = siloVault.convertToAssets(siloVault.balanceOf(address(this)));
if (notZero) {
_depositAssets(amounts, false);
}
}
/// @inheritdoc StrategyBase
function _previewDepositAssets(uint[] memory amountsMax)
internal
pure
override(StrategyBase)
returns (uint[] memory amountsConsumed, uint value)
{
amountsConsumed = new uint[](1);
amountsConsumed[0] = amountsMax[0];
value = amountsConsumed[0];
}
/// @inheritdoc StrategyBase
function _previewDepositAssets(
address[] memory, /*assets_*/
uint[] memory amountsMax
) internal pure override(StrategyBase) returns (uint[] memory amountsConsumed, uint value) {
return _previewDepositAssets(amountsMax);
}
/// @inheritdoc StrategyBase
function _assetsAmounts() internal view override returns (address[] memory assets_, uint[] memory amounts_) {
StrategyBaseStorage storage _$_ = _getStrategyBaseStorage();
assets_ = _$_._assets;
amounts_ = new uint[](1);
amounts_[0] = _$_.total;
}
/// @inheritdoc StrategyBase
function _processRevenue(
address[] memory, /*assets_*/
uint[] memory /*amountsRemaining*/
) internal pure override returns (bool needCompound) {
needCompound = true;
}
//endregion ----------------------------------- Strategy Base
//region ----------------------------------- Internal logic
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _genDesc(IFactory.Farm memory farm) internal view returns (string memory) {
return string.concat(
"Earn ",
CommonLib.implode(CommonLib.getSymbols(farm.rewardAssets), ", "),
" and supply APR by lending ",
IERC20Metadata(_getSilo(farm).asset()).symbol(),
" to Silo V2 + get Merkl rewards",
CommonLib.u2s(_getMarketId())
);
}
function _getMarketId() internal view returns (uint marketId) {
IFactory.Farm memory farm = _getFarm();
marketId = ISiloConfig(_getSilo(farm).config()).SILO_ID();
}
function _getSilo(IFactory.Farm memory farm) internal pure returns (ISilo) {
return ISilo(farm.addresses[0]);
}
function _getXSilo(IFactory.Farm memory farm) internal pure returns (address) {
return farm.addresses[1];
}
function _getGauge(IFactory.Farm memory farm) internal pure returns (address) {
return farm.addresses[2];
}
//endregion ----------------------------------- Internal logic
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {CommonLib} from "../../core/libs/CommonLib.sol";
import {IFactory} from "../../interfaces/IFactory.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
library SharedLib {
function shortAddress(address addr) internal pure returns (string memory) {
bytes memory s = bytes(Strings.toHexString(addr));
bytes memory shortAddr = new bytes(12);
shortAddr[0] = "0";
shortAddr[1] = "x";
shortAddr[2] = s[2];
shortAddr[3] = s[3];
shortAddr[4] = s[4];
shortAddr[5] = s[5];
shortAddr[6] = ".";
shortAddr[7] = ".";
shortAddr[8] = s[38];
shortAddr[9] = s[39];
shortAddr[10] = s[40];
shortAddr[11] = s[41];
return string(shortAddr);
}
/// @notice Universal implementation of {initVariants} for all farms
/// @param platform_ Platform address
/// @param strategyLogicId Strategy logic ID to filter farms
/// @param _genDesc Function to generate the variant description from the farm data
/// @return variants Array of variant descriptions
/// @return addresses Array of farm addresses
function initVariantsForFarm(
address platform_,
string memory strategyLogicId,
function(IFactory.Farm memory) internal view returns (string memory) _genDesc
)
internal
view
returns (string[] memory variants, address[] memory addresses, uint[] memory nums, int24[] memory ticks)
{
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 _total;
for (uint i; i < len; ++i) {
IFactory.Farm memory farm = farms[i];
if (farm.status == 0 && CommonLib.eq(farm.strategyLogicId, strategyLogicId)) {
++_total;
}
}
variants = new string[](_total);
nums = new uint[](_total);
_total = 0;
for (uint i; i < len; ++i) {
IFactory.Farm memory farm = farms[i];
if (farm.status == 0 && CommonLib.eq(farm.strategyLogicId, strategyLogicId)) {
nums[_total] = i;
variants[_total] = _genDesc(farm);
++_total;
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IFactory} from "../../interfaces/IFactory.sol";
import {IFarmingStrategy} from "../../interfaces/IFarmingStrategy.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";
import {StrategyBase, StrategyLib, IERC165} from "./StrategyBase.sol";
/// @title Base farming strategy
/// @author Alien Deployer (https://github.com/a17)
/// Changelog:
/// 1.3.4: liquidateRewards is virtual, use StrategyBase 2.5.0
/// 1.3.3: StrategyBase 2.2.0
/// 1.3.2: refreshFarmingAssets bugfix
/// 1.3.1: liquidateRewards fix
/// 1.3.0: use customPriceImpactTolerance
/// @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.3.4";
// 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 virtual override returns (uint earnedExchangeAsset) {
return StrategyLib.liquidateRewards(
platform(), exchangeAsset, rewardAssets_, rewardAmounts_, customPriceImpactTolerance()
);
}
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 {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {ConstantsLib} from "./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 formatAprInt(int apr) external pure returns (string memory formattedApr) {
int aprInt = apr * 100 / int(ConstantsLib.DENOMINATOR);
int aprFraction = (apr - aprInt * int(ConstantsLib.DENOMINATOR) / 100) / 10;
string memory delimiter = ".";
if (aprFraction < 10 || aprFraction > -10) {
delimiter = ".0";
}
formattedApr = string.concat(i2s2(aprInt), delimiter, i2s(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) public pure returns (string memory) {
return Strings.toString(num > 0 ? uint(num) : uint(-num));
}
function i2s2(int num) public pure returns (string memory) {
if (num >= 0) {
return Strings.toString(uint(num));
}
return string.concat("-", Strings.toString(uint(-num)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
library FarmMechanicsLib {
// Staking to gauge/farm to earn rewards
string internal constant CLASSIC = "Classic";
// Merkl protocol rewards calculated off-chain and credited periodically
string internal constant MERKL = "Merkl";
// Automatic farming without staking with on-chain calculated rewards
string internal constant AUTO = "Auto";
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @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)
/// @author dvpublic (https://github.com/dvpublic)
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();
error InsufficientBalance();
error IncorrectBalance();
error IncorrectLtv(uint ltv);
error TooLowValue(uint value);
error IncorrectAssetsList(address[] assets_, address[] expectedAssets_);
//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
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* 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[ERC 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.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 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
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);
event VaultWithSafeSharePriceAdded(address vault);
event VaultWithSafeSharePriceRemoved(address vault);
//endregion -- Events -----
//region --------------------------- Errors
error NotWhitelistedTransientCache();
//endregion --------------------------- Errors
/// @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 Price of vault share
/// @dev Price of 1.0 amount of vault token
/// @param vault Address of vault
/// @return price USD price with 18 decimals
/// @return safe Safe to use this price on-chain
function getVaultPrice(address vault) external view returns (uint price, bool safe);
/// @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 Get vaults that have organic safe share price that can be used on-chain
function vaultsWithSafeSharePrice() external view returns (address[] memory vaults);
/// @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;
/// @notice Remove oracle adapter from PriceReader
/// Only operator (multisig is operator too) can add adapter
/// @param adapter_ Address of price oracle proxy
function removeAdapter(address adapter_) external;
/// @notice Add vaults that have organic safe share price that can be used on-chain
/// Only operator (multisig is operator too) can add adapter
/// @param vaults Addresses of vaults
function addSafeSharePrices(address[] memory vaults) external;
/// @notice Remove vaults that have organic safe share price that can be used on-chain
/// Only operator (multisig is operator too) can add adapter
/// @param vaults Addresses of vaults
function removeSafeSharePrices(address[] memory vaults) external;
/// @notice Check if the user is whitelisted for using transient cache
function whitelistTransientCache(address user_) external view returns (bool);
/// @notice Add user to whitelist of users allowed to use the transient cache
function changeWhitelistTransientCache(address user, bool add) external;
/// @notice Save asset price to transient cache
/// @param asset Pass 0 to clear the cache
function preCalculatePriceTx(address asset) external;
/// @notice Save vault price to transient cache
/// Second call with the same vault will be ignored and won't not change the price
/// @param vault Pass 0 to clear the cache
function preCalculateVaultPriceTx(address vault) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {ISilo} from "./ISilo.sol";
interface ISiloConfig {
struct InitData {
/// @notice Can be address zero if deployer fees are not to be collected. If deployer address is zero then
/// deployer fee must be zero as well. Deployer will be minted an NFT that gives the right to claim deployer
/// fees. NFT can be transferred with the right to claim.
address deployer;
/// @notice Address of the hook receiver called on every before/after action on Silo. Hook contract also
/// implements liquidation logic and veSilo gauge connection.
address hookReceiver;
/// @notice Deployer's fee in 18 decimals points. Deployer will earn this fee based on the interest earned
/// by the Silo. Max deployer fee is set by the DAO. At deployment it is 15%.
uint deployerFee;
/// @notice DAO's fee in 18 decimals points. DAO will earn this fee based on the interest earned
/// by the Silo. Acceptable fee range fee is set by the DAO. Default at deployment is 5% - 50%.
uint daoFee;
/// @notice Address of the first token
address token0;
/// @notice Address of the solvency oracle. Solvency oracle is used to calculate LTV when deciding if borrower
/// is solvent or should be liquidated. Solvency oracle is optional and if not set price of 1 will be assumed.
address solvencyOracle0;
/// @notice Address of the maxLtv oracle. Max LTV oracle is used to calculate LTV when deciding if borrower
/// can borrow given amount of assets. Max LTV oracle is optional and if not set it defaults to solvency
/// oracle. If neither is set price of 1 will be assumed.
address maxLtvOracle0;
/// @notice Address of the interest rate model
address interestRateModel0;
/// @notice Maximum LTV for first token. maxLTV is in 18 decimals points and is used to determine, if borrower
/// can borrow given amount of assets. MaxLtv is in 18 decimals points. MaxLtv must be lower or equal to LT.
uint maxLtv0;
/// @notice Liquidation threshold for first token. LT is used to calculate solvency. LT is in 18 decimals
/// points. LT must not be lower than maxLTV.
uint lt0;
/// @notice minimal acceptable LTV after liquidation, in 18 decimals points
uint liquidationTargetLtv0;
/// @notice Liquidation fee for the first token in 18 decimals points. Liquidation fee is what liquidator earns
/// for repaying insolvent loan.
uint liquidationFee0;
/// @notice Flashloan fee sets the cost of taking a flashloan in 18 decimals points
uint flashloanFee0;
/// @notice Indicates if a beforeQuote on oracle contract should be called before quoting price
bool callBeforeQuote0;
/// @notice Address of the second token
address token1;
/// @notice Address of the solvency oracle. Solvency oracle is used to calculate LTV when deciding if borrower
/// is solvent or should be liquidated. Solvency oracle is optional and if not set price of 1 will be assumed.
address solvencyOracle1;
/// @notice Address of the maxLtv oracle. Max LTV oracle is used to calculate LTV when deciding if borrower
/// can borrow given amount of assets. Max LTV oracle is optional and if not set it defaults to solvency
/// oracle. If neither is set price of 1 will be assumed.
address maxLtvOracle1;
/// @notice Address of the interest rate model
address interestRateModel1;
/// @notice Maximum LTV for first token. maxLTV is in 18 decimals points and is used to determine,
/// if borrower can borrow given amount of assets. maxLtv is in 18 decimals points
uint maxLtv1;
/// @notice Liquidation threshold for first token. LT is used to calculate solvency. LT is in 18 decimals points
uint lt1;
/// @notice minimal acceptable LTV after liquidation, in 18 decimals points
uint liquidationTargetLtv1;
/// @notice Liquidation fee is what liquidator earns for repaying insolvent loan.
uint liquidationFee1;
/// @notice Flashloan fee sets the cost of taking a flashloan in 18 decimals points
uint flashloanFee1;
/// @notice Indicates if a beforeQuote on oracle contract should be called before quoting price
bool callBeforeQuote1;
}
struct ConfigData {
uint daoFee;
uint deployerFee;
address silo;
address token;
address protectedShareToken;
address collateralShareToken;
address debtShareToken;
address solvencyOracle;
address maxLtvOracle;
address interestRateModel;
uint maxLtv;
uint lt;
uint liquidationTargetLtv;
uint liquidationFee;
uint flashloanFee;
address hookReceiver;
bool callBeforeQuote;
}
struct DepositConfig {
address silo;
address token;
address collateralShareToken;
address protectedShareToken;
uint daoFee;
uint deployerFee;
address interestRateModel;
}
error OnlySilo();
error OnlySiloOrTokenOrHookReceiver();
error WrongSilo();
error OnlyDebtShareToken();
error DebtExistInOtherSilo();
error FeeTooHigh();
/// @dev It should be called on debt transfer (debt share token transfer).
/// In the case if the`_recipient` doesn't have configured a collateral silo,
/// it will be set to the collateral silo of the `_sender`.
/// @param _sender sender address
/// @param _recipient recipient address
function onDebtTransfer(address _sender, address _recipient) external;
/// @notice Set collateral silo.
/// @dev Revert if msg.sender is not a SILO_0 or SILO_1.
/// @dev Always set collateral silo the same as msg.sender.
/// @param _borrower borrower address
function setThisSiloAsCollateralSilo(address _borrower) external;
/// @notice Set collateral silo
/// @dev Revert if msg.sender is not a SILO_0 or SILO_1.
/// @dev Always set collateral silo opposite to the msg.sender.
/// @param _borrower borrower address
function setOtherSiloAsCollateralSilo(address _borrower) external;
/// @notice Accrue interest for the silo
/// @param _silo silo for which accrue interest
function accrueInterestForSilo(address _silo) external;
/// @notice Accrue interest for both silos (SILO_0 and SILO_1 in a config)
function accrueInterestForBothSilos() external;
/// @notice Retrieves the collateral silo for a specific borrower.
/// @dev As a user can deposit into `Silo0` and `Silo1`, this property specifies which Silo
/// will be used as collateral for the debt. Later on, it will be used for max LTV and solvency checks.
/// After being set, the collateral silo is never set to `address(0)` again but such getters as
/// `getConfigsForSolvency`, `getConfigsForBorrow`, `getConfigsForWithdraw` will return empty
/// collateral silo config if borrower doesn't have debt.
///
/// In the SiloConfig collateral silo is set by the following functions:
/// `onDebtTransfer` - only if the recipient doesn't have collateral silo set (inherits it from the sender)
/// This function is called on debt share token transfer (debt transfer).
/// `setThisSiloAsCollateralSilo` - sets the same silo as the one that calls the function.
/// `setOtherSiloAsCollateralSilo` - sets the opposite silo as collateral from the one that calls the function.
///
/// In the Silo collateral silo is set by the following functions:
/// `borrow` - always sets opposite silo as collateral.
/// If Silo0 borrows, then Silo1 will be collateral and vice versa.
/// `borrowSameAsset` - always sets the same silo as collateral.
/// `switchCollateralToThisSilo` - always sets the same silo as collateral.
/// @param _borrower The address of the borrower for which the collateral silo is being retrieved
/// @return collateralSilo The address of the collateral silo for the specified borrower
function borrowerCollateralSilo(address _borrower) external view returns (address collateralSilo);
/// @notice Retrieves the silo ID
/// @dev Each silo is assigned a unique ID. ERC-721 token is minted with identical ID to deployer.
/// An owner of that token receives the deployer fees.
/// @return siloId The ID of the silo
function SILO_ID() external view returns (uint siloId); // solhint-disable-line func-name-mixedcase
/// @notice Retrieves the addresses of the two silos
/// @return silo0 The address of the first silo
/// @return silo1 The address of the second silo
function getSilos() external view returns (address silo0, address silo1);
/// @notice Retrieves the asset associated with a specific silo
/// @dev This function reverts for incorrect silo address input
/// @param _silo The address of the silo for which the associated asset is being retrieved
/// @return asset The address of the asset associated with the specified silo
function getAssetForSilo(address _silo) external view returns (address asset);
/// @notice Verifies if the borrower has debt in other silo by checking the debt share token balance
/// @param _thisSilo The address of the silo in respect of which the debt is checked
/// @param _borrower The address of the borrower for which the debt is checked
/// @return hasDebt true if the borrower has debt in other silo
function hasDebtInOtherSilo(address _thisSilo, address _borrower) external view returns (bool hasDebt);
/// @notice Retrieves the debt silo associated with a specific borrower
/// @dev This function reverts if debt present in two silo (should not happen)
/// @param _borrower The address of the borrower for which the debt silo is being retrieved
function getDebtSilo(address _borrower) external view returns (address debtSilo);
/// @notice Retrieves configuration data for both silos. First config is for the silo that is asking for configs.
/// @param borrower borrower address for which debtConfig will be returned
/// @return collateralConfig The configuration data for collateral silo (empty if there is no debt).
/// @return debtConfig The configuration data for debt silo (empty if there is no debt).
function getConfigsForSolvency(address borrower)
external
view
returns (ConfigData memory collateralConfig, ConfigData memory debtConfig);
/// @notice Retrieves configuration data for a specific silo
/// @dev This function reverts for incorrect silo address input.
/// @param _silo The address of the silo for which configuration data is being retrieved
/// @return config The configuration data for the specified silo
function getConfig(address _silo) external view returns (ConfigData memory config);
/// @notice Retrieves configuration data for a specific silo for withdraw fn.
/// @dev This function reverts for incorrect silo address input.
/// @param _silo The address of the silo for which configuration data is being retrieved
/// @return depositConfig The configuration data for the specified silo (always config for `_silo`)
/// @return collateralConfig The configuration data for the collateral silo (empty if there is no debt)
/// @return debtConfig The configuration data for the debt silo (empty if there is no debt)
function getConfigsForWithdraw(
address _silo,
address _borrower
)
external
view
returns (DepositConfig memory depositConfig, ConfigData memory collateralConfig, ConfigData memory debtConfig);
/// @notice Retrieves configuration data for a specific silo for borrow fn.
/// @dev This function reverts for incorrect silo address input.
/// @param _debtSilo The address of the silo for which configuration data is being retrieved
/// @return collateralConfig The configuration data for the collateral silo (always other than `_debtSilo`)
/// @return debtConfig The configuration data for the debt silo (always config for `_debtSilo`)
function getConfigsForBorrow(address _debtSilo)
external
view
returns (ConfigData memory collateralConfig, ConfigData memory debtConfig);
/// @notice Retrieves fee-related information for a specific silo
/// @dev This function reverts for incorrect silo address input
/// @param _silo The address of the silo for which fee-related information is being retrieved.
/// @return daoFee The DAO fee percentage in 18 decimals points.
/// @return deployerFee The deployer fee percentage in 18 decimals points.
/// @return flashloanFee The flashloan fee percentage in 18 decimals points.
/// @return asset The address of the asset associated with the specified silo.
function getFeesWithAsset(address _silo)
external
view
returns (uint daoFee, uint deployerFee, uint flashloanFee, address asset);
/// @notice Retrieves share tokens associated with a specific silo
/// @dev This function reverts for incorrect silo address input
/// @param _silo The address of the silo for which share tokens are being retrieved
/// @return protectedShareToken The address of the protected (non-borrowable) share token
/// @return collateralShareToken The address of the collateral share token
/// @return debtShareToken The address of the debt share token
function getShareTokens(address _silo)
external
view
returns (address protectedShareToken, address collateralShareToken, address debtShareToken);
/// @notice Retrieves the share token and the silo token associated with a specific silo
/// @param _silo The address of the silo for which the share token and silo token are being retrieved
/// @param _collateralType The type of collateral
/// @return shareToken The address of the share token (collateral or protected collateral)
/// @return asset The address of the silo token
function getCollateralShareTokenAndAsset(
address _silo,
ISilo.CollateralType _collateralType
) external view returns (address shareToken, address asset);
/// @notice Retrieves the share token and the silo token associated with a specific silo
/// @param _silo The address of the silo for which the share token and silo token are being retrieved
/// @return shareToken The address of the share token (debt)
/// @return asset The address of the silo token
function getDebtShareTokenAndAsset(address _silo) external view returns (address shareToken, address asset);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IDistributionManager} from "./IDistributionManager.sol";
/// @notice Actually it's interface of SiloIncentivesControllerGaugeLike
interface ISiloIncentivesController is IDistributionManager {
/**
* @dev Claims reward for an user to the desired address, on all the assets of the lending pool,
* accumulating the pending rewards
* @param _to Address that will be receiving the rewards
* @return accruedRewards
*/
function claimRewards(address _to) external returns (AccruedRewards[] memory accruedRewards);
/**
* @dev Claims reward for an user to the desired address, on all the assets of the lending pool,
* accumulating the pending rewards
* @param _to Address that will be receiving the rewards
* @param _programNames The incentives program names
* @return accruedRewards
*/
function claimRewards(
address _to,
string[] calldata _programNames
) external returns (AccruedRewards[] memory accruedRewards);
function SHARE_TOKEN() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
interface ISilo is IERC4626 {
error NotEnoughLiquidity();
/// @dev There are 2 types of accounting in the system: for non-borrowable collateral deposit called "protected" and
/// for borrowable collateral deposit called "collateral". System does
/// identical calculations for each type of accounting but it uses different data. To avoid code duplication
/// this enum is used to decide which data should be read.
enum CollateralType {
Protected,
Collateral
}
/// @notice Implements IERC4626.deposit for protected (non-borrowable) collateral and collateral
/// @dev Reverts for debt asset type
function deposit(uint _assets, address _receiver, CollateralType collateralType) external returns (uint shares);
/// @notice Allows an address to borrow a specified amount of assets
/// @param _assets Amount of assets to borrow
/// @param _receiver Address receiving the borrowed assets
/// @param _borrower Address responsible for the borrowed assets
/// @return shares Amount of shares equivalent to the borrowed assets
function borrow(uint _assets, address _receiver, address _borrower) external returns (uint shares);
/// @notice Repays a given asset amount and returns the equivalent number of shares
/// @param _assets Amount of assets to be repaid
/// @param _borrower Address of the borrower whose debt is being repaid
/// @return shares The equivalent number of shares for the provided asset amount
function repay(uint _assets, address _borrower) external returns (uint shares);
/// @notice Implements IERC4626.withdraw for protected (non-borrowable) collateral and collateral
/// @dev Reverts for debt asset type
function withdraw(
uint _assets,
address _receiver,
address _owner,
CollateralType collateralType
) external returns (uint shares);
/// @notice Accrues interest for the asset and returns the accrued interest amount
/// @return accruedInterest The total interest accrued during this operation
function accrueInterest() external returns (uint accruedInterest);
/// @inheritdoc IERC4626
/// @dev For protected (non-borrowable) collateral and debt, use:
/// `convertToAssets(uint256 _shares, AssetType _assetType)` with `AssetType.Protected` or `AssetType.Debt`
function convertToAssets(uint _shares) external view returns (uint assets);
function convertToAssets(uint256 _shares, CollateralType _assetType) external view returns (uint256 assets);
function asset() external view returns (address assetTokenAddres);
/// @notice Fetches the silo configuration contract
/// @return siloConfig Address of the configuration contract associated with the silo
function config() external view returns (address siloConfig);
/// @notice Calculates the maximum amount of assets that can be borrowed by the given address
/// @param _borrower Address of the potential borrower
/// @return maxAssets Maximum amount of assets that the borrower can borrow, this value is underestimated
/// That means, in some cases when you borrow maxAssets, you will be able to borrow again eg. up to 2wei
/// Reason for underestimation is to return value that will not cause borrow revert
function maxBorrow(address _borrower) external view returns (uint maxAssets);
/// @notice Calculates the maximum amount an address can repay based on their debt shares
/// @param _borrower Address of the borrower
/// @return assets Maximum amount of assets the borrower can repay
function maxRepay(address _borrower) external view returns (uint assets);
function getLiquidity() external view returns (uint256 liquidity);
function maxWithdraw(address _owner, CollateralType _collateralType) external view returns (uint256 maxAssets);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC165} from "@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 StrategyProtocols(string[]);
event SpecificName(string);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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;
uint customPriceImpactTolerance;
/// @inheritdoc IStrategy
uint fuseOn;
/// @inheritdoc IStrategy
string[] protocols;
string specific;
}
enum FuseMode {
FUSE_OFF_0,
/// @notice Fuse mode is on (emergency stop was called).
/// All assets were transferred from the underlying pool to the strategy balance, no deposits are allowed.
FUSE_ON_1
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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 5 decimals. 100_000 - 100% APR, 9_955 - 9.96% APR.
function lastApr() external view returns (uint);
/// @dev Last APR of compounded assets registered by HardWork.
/// Can be used on-chain.
/// @return APR with 5 decimals. 100_000 - 100% APR, 9_955 - 9.96% APR.
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);
/// @notice Custom price impact tolerance instead default need for specific cases where liquidity in pools is low
function customPriceImpactTolerance() external view returns (uint);
/// @notice Total amount of assets available in the lending protocol for withdraw
/// It's normal situation when user is not able to withdraw all
/// because there are not enough reserves available in the protocol right now
/// @dev This function is replaced by more flexible maxWithdrawAssets(uint mode) function.
function maxWithdrawAssets() external view returns (uint[] memory amounts);
/// @notice Total amount of assets available in the lending protocol for withdraw
/// It's normal situation when user is not able to withdraw all
/// because there are not enough reserves available in the protocol right now
/// @param mode 0 - Return amount that can be withdrawn in assets
/// 1 - Return amount that can be withdrawn in underlying
/// @return amounts Empty array (zero length) is returned if all available amount can be withdrawn
function maxWithdrawAssets(uint mode) external view returns (uint[] memory amounts);
/// @notice Underlying pool TVL in the terms of USD
function poolTvl() external view returns (uint tvlUsd);
/// @notice return FUSE_ON_1 if emergency was called and all actives were transferred to the vault
function fuseMode() external view returns (uint);
/// @notice Maximum amounts of assets that can be deposited into the strategy
/// @return amounts Empty array (zero length) is returned if there are no limits on deposits
function maxDepositAssets() external view returns (uint[] memory amounts);
/// @notice Show strategy protocols
function protocols() external view returns (string[] memory);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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 Amounts 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 Consumed 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 Amount 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 Amount 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;
/// @notice Custom price impact tolerance instead default need for specific cases where low liquidity in pools
/// @param priceImpactTolerance Tolerance percent with 100_000 DENOMINATOR. 4_000 == 4%
function setCustomPriceImpactTolerance(uint priceImpactTolerance) external;
/// @notice Set custom strategy protocols
/// @param protocols_ Row format is: defi_organization_id:protocol_id from Stability Library.
function setProtocols(string[] calldata protocols_) external;
/// @notice Set custom specific name
function setSpecificName(string memory specific) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice Sonic 0x4451765739b2D7BCe5f8BC95Beaf966c45E1Dcc9
interface IXSilo {
function MAX_REDEEM_DURATION_CAP() external view returns (uint256);
function MAX_REDEEM_RATIO() external view returns (uint256);
function acceptOwnership() external;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function asset() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function cancelRedeem(uint256 _redeemIndex) external;
function convertToAssets(uint256 shares) external view returns (uint256);
function convertToShares(uint256 assets) external view returns (uint256);
function decimals() external view returns (uint8);
function deposit(uint256 _assets, address _receiver) external returns (uint256 shares);
function finalizeRedeem(uint256 redeemIndex) external;
function getAmountByVestingDuration(uint256 _xSiloAmount, uint256 _duration)
external
view
returns (uint256 siloAmountAfterVesting);
function getAmountInByVestingDuration(
uint256 _xSiloAfterVesting,
uint256 _duration
) external view returns (uint256 xSiloAmountIn);
function getUserRedeem(address _userAddress, uint256 _redeemIndex)
external
view
returns (
uint256 currentSiloAmount,
uint256 xSiloAmount,
uint256 siloAmountAfterVesting,
uint256 endTime
);
function getUserRedeemsBalance(address _userAddress) external view returns (uint256 redeemingSiloAmount);
function getUserRedeemsLength(address _userAddress) external view returns (uint256);
function getXAmountByVestingDuration(
uint256 _xSiloAmount,
uint256 _duration
) external view returns (uint256 xSiloAfterVesting);
function maxDeposit(address) external view returns (uint256);
function maxMint(address) external view returns (uint256);
function maxRedeem(address _owner) external view returns (uint256 shares);
function maxRedeemDuration() external view returns (uint256);
function maxWithdraw(address _owner) external view returns (uint256 assets);
function minRedeemDuration() external view returns (uint256);
function minRedeemRatio() external view returns (uint256);
function mint(uint256 _shares, address _receiver) external returns (uint256 assets);
function name() external view returns (string memory);
function notificationReceiver() external view returns (address);
function owner() external view returns (address);
function pendingLockedSilo() external view returns (uint256);
function pendingOwner() external view returns (address);
function previewDeposit(uint256 assets) external view returns (uint256);
function previewMint(uint256 shares) external view returns (uint256);
function previewRedeem(uint256 _shares) external view returns (uint256 assets);
function previewWithdraw(uint256 _assets) external view returns (uint256 shares);
function redeem(uint256 _shares, address _receiver, address _owner) external returns (uint256 assets);
/// @notice on redeem, `_xSiloAmount` of shares are burned, so it is no longer available
/// when cancel, `_xSiloAmount` of shares will be minted back
function redeemSilo(uint256 _xSiloAmountToBurn, uint256 _duration) external returns (uint256 siloAmountAfterVesting);
function renounceOwnership() external;
function setNotificationReceiver(
address _notificationReceiver,
bool _allProgramsStopped
) external;
function setStream(address _stream) external;
function stream() external view returns (address);
function symbol() external view returns (string memory);
function totalAssets() external view returns (uint256 total);
function totalSupply() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function transferOwnership(address newOwner) external;
function updateRedeemSettings(
uint256 _minRedeemRatio,
uint256 _minRedeemDuration,
uint256 _maxRedeemDuration
) external;
function userRedeems(address _user) external view returns (RedeemInfo[] memory);
function withdraw(
uint256 _assets,
address _receiver,
address _owner
) external returns (uint256 shares);
struct RedeemInfo {
uint256 currentSiloAmount;
uint256 xSiloAmountToBurn;
uint256 siloAmountAfterVesting;
uint256 endTime;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {StrategyBase, IERC165, SafeERC20, IERC20} from "./StrategyBase.sol";
import {IMerklStrategy} from "../../interfaces/IMerklStrategy.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";
import {IMerklDistributor} from "../../integrations/merkl/IMerklDistributor.sol";
/// @title Base for Merkl strategies
/// Changelog:
/// 1.1.0: add claimToMultisig
/// @author Alien Deployer (https://github.com/a17)
abstract contract MerklStrategyBase is StrategyBase, IMerklStrategy {
using SafeERC20 for IERC20;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Version of StrategyBase implementation
string public constant VERSION_MERKL_STRATEGY_BASE = "1.1.0";
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RESTRICTED ACTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @inheritdoc IMerklStrategy
function toggleDistributorUserOperator(address distributor, address operator) external onlyOperator {
IMerklDistributor(distributor).toggleOperator(address(this), operator);
}
/// @inheritdoc IMerklStrategy
function claimToMultisig(
address distributor,
address[] calldata tokens,
uint[] calldata amounts,
bytes32[][] calldata proofs
) external onlyOperator {
address multisig = IPlatform(platform()).multisig();
uint len = tokens.length;
address[] memory users = new address[](len);
uint[] memory balanceBefore = new uint[](len);
for (uint i; i < len; ++i) {
balanceBefore[i] = IERC20(tokens[i]).balanceOf(address(this));
users[i] = address(this);
}
IMerklDistributor(distributor).claim(users, tokens, amounts, proofs);
for (uint i; i < len; ++i) {
uint got = IERC20(tokens[i]).balanceOf(address(this)) - balanceBefore[i];
IERC20(tokens[i]).safeTransfer(multisig, got);
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* VIEW FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IMerklStrategy).interfaceId || super.supportsInterface(interfaceId);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
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 silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// 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";
string internal constant SWAPX_FARM = "SwapX Farm";
string internal constant SILO_FARM = "Silo Farm";
string internal constant ALM_SHADOW_FARM = "ALM Shadow Farm";
string internal constant SILO_LEVERAGE = "Silo Leverage";
string internal constant SILO_ADVANCED_LEVERAGE = "Silo Advanced Leverage";
string internal constant GAMMA_EQUALIZER_FARM = "Gamma Equalizer Farm";
string internal constant ICHI_EQUALIZER_FARM = "Ichi Equalizer Farm";
string internal constant EULER_MERKL_FARM = "Euler Merkl Farm";
string internal constant SILO = "Silo";
string internal constant AAVE = "Aave";
string internal constant EULER = "Euler"; // https://euler.finance/
string internal constant SILO_MANAGED_FARM = "Silo Managed Farm";
string internal constant SILO_ALMF_FARM = "Silo Advanced Leverage Merkl Farm";
string internal constant AAVE_MERKL_FARM = "Aave Merkl Farm";
string internal constant COMPOUND_V2 = "Compound V2";
string internal constant SILO_MANAGED_MERKL_FARM = "Silo Managed Merkl Farm";
string internal constant SILO_MERKL_FARM = "Silo Merkl Farm"; // SiMerklF
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
library VaultTypeLib {
string internal constant COMPOUNDING = "Compounding";
//string internal constant REWARDING = "Rewarding";
//string internal constant REWARDING_MANAGED = "Rewarding Managed";
string internal constant MULTIVAULT = "MultiVault";
string internal constant METAVAULT = "MetaVault";
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {EnumerableSet} from "@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 StrategyImplementationIsNotAvailable();
error YouDontHaveEnoughTokens(uint userBalance, uint requireBalance, address payToken);
error SuchVaultAlreadyDeployed(bytes32 key);
error NotActiveVault();
error UpgradeDenied(bytes32 _hash);
error AlreadyLastVersion(bytes32 _hash);
error NotStrategy();
//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 => mapping(uint => uint)) __deprecated1;
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
)
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 initialization addresses for deployVaultAndStrategy method
/// @param vaultInitNums Vault initialization uint numbers for deployVaultAndStrategy method
/// @param strategyInitAddresses Strategy initialization addresses for deployVaultAndStrategy method
/// @param strategyInitNums Strategy initialization uint numbers for deployVaultAndStrategy method
/// @param strategyInitTicks Strategy initialization 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 view returns (bytes32);
/// @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 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);
//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 vault type implementation
/// Operator can add new vault type. Governance or multisig can change existing vault type config.
/// @param vaultType Vault type string ID (Compounding, etc)
/// @param implementation Address of implementation
function setVaultImplementation(string memory vaultType, address implementation) 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;
//endregion -- Write functions -----
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @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)
/// @author ruby (https://github.com/alexandersazonof)
interface IPlatform {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
error AlreadyAnnounced();
error SameVersion();
error NoNewVersion();
error UpgradeTimerIsNotOver(uint TimerTimestamp);
error IncorrectFee(uint minFee, uint maxFee);
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,
address vaultManager_,
address strategyLogic_,
address,
address hardWorker,
address rebalancer,
address zap,
address bridge
);
event OperatorAdded(address operator);
event OperatorRemoved(address operator);
event FeesChanged(uint fee, uint, uint, uint);
event NewAmmAdapter(string id, address proxy);
event EcosystemRevenueReceiver(address receiver);
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_);
event RevenueRouter(address revenueRouter_);
event MetaVaultFactory(address metaVaultFactory);
event VaultPriceOracle(address vaultPriceOracle_);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DATA TYPES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
struct PlatformUpgrade {
string newVersion;
address[] proxies;
address[] newImplementations;
}
struct PlatformSettings {
uint fee;
}
struct AmmAdapter {
string id;
address proxy;
}
struct SetupAddresses {
address factory;
address priceReader;
address swapper;
address vaultManager;
address strategyLogic;
address targetExchangeAsset;
address hardWorker;
address zap;
address revenueRouter;
address metaVaultFactory;
address vaultPriceOracle;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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 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 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 Platform revenue distributor
/// @return Address of the revenue distributor proxy
function revenueRouter() external view returns (address);
/// @notice Factory of MetaVaults
/// @return Address of the MetaVault factory
function metaVaultFactory() external view returns (address);
/// @notice vaultPriceOracle
/// @return Address of the vault price oracle
function vaultPriceOracle() external view returns (address);
/// @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);
/// @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.
function getFees() external view returns (uint fee, uint, uint, uint);
/// @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 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 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] deprecated
/// platformAddresses[4] deprecated
/// 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
);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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 execute pending platform upgrade
function upgrade() external;
/// @notice Cancel pending platform upgrade
/// Only operator (multisig is operator too) can execute 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;
/// @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 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 Set vault price oracle
/// @param vaultPriceOracle_ Address of the vault price oracle
function setupVaultPriceOracle(address vaultPriceOracle_) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @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;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
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 Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @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));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}// 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.28;
import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Controllable, IControllable} from "../../core/base/Controllable.sol";
import {StrategyLib} from "../libs/StrategyLib.sol";
import {IStrategy} from "../../interfaces/IStrategy.sol";
import {IVault} from "../../interfaces/IVault.sol";
/// @dev Base universal strategy
/// Changelog:
/// 2.6.0: protocols, setSpecific
/// 2.5.1: add maxWithdrawAssets(uint) - #360
/// 2.5.0: add maxDepositAssets - #330
/// 2.4.0: add poolTvl, maxWithdrawAssets - #326
/// 2.3.0: add fuseMode - #305
/// 2.2.0: extractFees use RevenueRouter
/// 2.1.3: call hardWorkMintFeeCallback always
/// 2.1.2: call hardWorkMintFeeCallback only on positive amounts
/// 2.1.1: extractFees fixed
/// 2.1.0: customPriceImpactTolerance
/// 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.6.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_);
}
//region -------------------- Restricted actions
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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, __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
if (StrategyLib.isPositiveAmountInArray(__amounts)) {
IVault(_vault).hardWorkMintFeeCallback(__assets, __amounts);
} else {
(, uint[] memory __assetsAmounts) = assetsAmounts();
uint[] memory virtualRevenueAmounts = new uint[](__assets.length);
virtualRevenueAmounts[0] = __assetsAmounts[0] * (block.timestamp - $.lastHardWork) / 365 days / 7;
IVault(_vault).hardWorkMintFeeCallback(__assets, virtualRevenueAmounts);
}
// 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));
// Activate fuse mode. In the fuse mode all assets are transferred
// from the underlying pool to the strategy balance, no deposits are allowed after that.
_getStrategyBaseStorage().fuseOn = uint(IStrategy.FuseMode.FUSE_ON_1);
}
/// @inheritdoc IStrategy
function setCustomPriceImpactTolerance(uint priceImpactTolerance) external onlyOperator {
StrategyBaseStorage storage $ = _getStrategyBaseStorage();
$.customPriceImpactTolerance = priceImpactTolerance;
}
/// @inheritdoc IStrategy
function setProtocols(string[] memory protocols_) external onlyOperator {
StrategyBaseStorage storage $ = _getStrategyBaseStorage();
$.protocols = protocols_;
emit StrategyProtocols(protocols_);
}
/// @inheritdoc IStrategy
function setSpecificName(string memory specific) external onlyOperator {
StrategyBaseStorage storage $ = _getStrategyBaseStorage();
$.specific = specific;
emit SpecificName(specific);
}
//endregion -------------------- Restricted actions
//region -------------------- View functions
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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;
}
/// @inheritdoc IStrategy
function customPriceImpactTolerance() public view returns (uint) {
return _getStrategyBaseStorage().customPriceImpactTolerance;
}
/// @notice IStrategy
function maxWithdrawAssets() public view virtual returns (uint[] memory amounts) {
return maxWithdrawAssets(0);
}
/// @notice IStrategy
function maxWithdrawAssets(uint /*mode*/ ) public view virtual returns (uint[] memory amounts) {
// by default zero-length array is returned to indicate that all available amounts can be withdrawn
return amounts;
}
/// @inheritdoc IStrategy
function poolTvl() public view virtual returns (uint tvlUsd) {
// by default max uint is returned to indicate that pool TVL is not calculated
return type(uint).max;
}
/// @notice IStrategy
function maxDepositAssets() public view virtual returns (uint[] memory amounts) {
// by default zero-length array is returned to indicate that there are no limits on deposit amounts
return amounts;
}
/// @notice IStrategy
function protocols() external view returns (string[] memory) {
return _getStrategyBaseStorage().protocols;
}
//endregion -------------------- View functions
//region -------------------- Default implementations
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* Default implementations */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @inheritdoc IStrategy
function fuseMode() external view returns (uint) {
return _getStrategyBaseStorage().fuseOn;
}
/// @dev Invest underlying asset. Asset must be already on strategy contract balance.
/// @return Consumed amounts of invested assets
function _depositUnderlying(uint /*amount*/ ) internal virtual returns (uint[] memory /*amountsConsumed*/ ) {
revert(_getStrategyBaseStorage()._underlying == address(0) ? "no underlying" : "not implemented");
}
/// @dev Withdraw 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();
}
}
/// @inheritdoc IStrategy
function getSpecificName() external view virtual returns (string memory, bool) {
return (_getStrategyBaseStorage().specific, true);
}
//endregion -------------------- Default implementations
//region -------------------- Must be implemented by derived contracts
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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);
}
//endregion -------------------- Must be implemented by derived contracts
//region -------------------- Internal logic
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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();
}
}
//endregion -------------------- Internal logic
}// 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
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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
pragma solidity ^0.8.23;
interface IDistributionManager {
struct AccruedRewards {
uint amount;
bytes32 programId;
address rewardToken;
}
struct IncentiveProgramDetails {
uint256 index;
address rewardToken;
uint104 emissionPerSecond;
uint40 lastUpdateTimestamp;
uint40 distributionEnd;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC4626.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IMerklStrategy {
/// @notice Toggle user operator status on Merkl Distributor
/// @dev Only whitelisted operators can claim Merkl rewards for user (strategy address).
/// Only Stability Platform operators can call this
/// @param distributor Address of Merkl Distributor contract
/// @param operator Address of Merkl rewards claimer that can be HardWorker.dedicatedServerMsgSender
function toggleDistributorUserOperator(address distributor, address operator) external;
/// @notice Claim rewards to multisig for future distribution
/// Only Stability Platform operators can call this
function claimToMultisig(
address distributor,
address[] calldata tokens,
uint[] calldata amounts,
bytes32[][] calldata proofs
) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
interface IMerklDistributor {
error NotWhitelisted();
/// @notice Toggles whitelisting for a given user and a given operator
function toggleOperator(address user, address operator) external;
/// @notice Claims rewards for a given set of users
/// @dev Anyone may call this function for anyone else, funds go to destination regardless, it's just a question of
/// who provides the proof and pays the gas: `msg.sender` is used only for addresses that require a trusted operator
/// @param users Recipient of tokens
/// @param tokens ERC20 claimed
/// @param amounts Amount of tokens that will be sent to the corresponding users
/// @param proofs Array of hashes bridging from a leaf `(hash of user | token | amount)` to the Merkle root
function claim(
address[] calldata users,
address[] calldata tokens,
uint[] calldata amounts,
bytes32[][] calldata proofs
) external;
/// @notice Same as the function above except that for each token claimed, the caller may set different
/// recipients for rewards and pass arbitrary data to the reward recipient on claim
/// @dev Only a `msg.sender` calling for itself can set a different recipient for the token rewards
/// within the context of a call to claim
/// @dev Non-zero recipient addresses given by the `msg.sender` can override any previously set reward address
function claimWithRecipient(
address[] calldata users,
address[] calldata tokens,
uint256[] calldata amounts,
bytes32[][] calldata proofs,
address[] calldata recipients,
bytes[] memory datas
) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";
/**
* @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.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* The following types are supported:
*
* - `bytes32` (`Bytes32Set`) since v3.3.0
* - `address` (`AddressSet`) since v3.3.0
* - `uint256` (`UintSet`) since v3.3.0
* - `string` (`StringSet`) since v5.4.0
* - `bytes` (`BytesSet`) since v5.4.0
*
* [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 Removes all the values from a set. O(n).
*
* WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
* using it may render the function uncallable if the set grows to the point where clearing it consumes too much
* gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) private view returns (bytes32[] memory) {
unchecked {
end = Math.min(end, _length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
// 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @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;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
bytes32[] memory result;
assembly ("memory-safe") {
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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @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;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
address[] memory result;
assembly ("memory-safe") {
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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @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;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
struct StringSet {
// Storage of set values
string[] _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(string 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(StringSet storage set, string memory value) internal 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(StringSet storage set, string memory value) internal 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) {
string memory 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(StringSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(StringSet storage set, string memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(StringSet storage set) internal 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(StringSet storage set, uint256 index) internal view returns (string memory) {
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(StringSet storage set) internal view returns (string[] memory) {
return set._values;
}
/**
* @dev Return a slice of the 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(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
string[] memory result = new string[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
struct BytesSet {
// Storage of set values
bytes[] _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(bytes 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(BytesSet storage set, bytes memory value) internal 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(BytesSet storage set, bytes memory value) internal 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) {
bytes memory 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(BytesSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(BytesSet storage set) internal 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(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
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(BytesSet storage set) internal view returns (bytes[] memory) {
return set._values;
}
/**
* @dev Return a slice of the 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(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes[] memory result = new bytes[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(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.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* 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 {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 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 low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, 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 ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
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⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev 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) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @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
// OpenZeppelin Contracts (last updated v5.1.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/bool 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);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(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 {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {SlotsLib} from "../libs/SlotsLib.sol";
import {IControllable} from "../../interfaces/IControllable.sol";
import {IPlatform} from "../../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.1";
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 {
require(platform_ != address(0) && IPlatform(platform_).multisig() != address(0), 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 {
require(IPlatform(platform()).governance() == msg.sender, NotGovernance());
}
function _requireMultisig() internal view {
require(IPlatform(platform()).multisig() == msg.sender, NotMultisig());
}
function _requireGovernanceOrMultisig() internal view {
IPlatform _platform = IPlatform(platform());
require(
_platform.governance() == msg.sender || _platform.multisig() == msg.sender, NotGovernanceAndNotMultisig()
);
}
function _requireOperator() internal view {
require(IPlatform(platform()).isOperator(msg.sender), NotOperator());
}
function _requireFactory() internal view {
require(IPlatform(platform()).factory() == msg.sender, NotFactory());
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ConstantsLib} from "../../core/libs/ConstantsLib.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";
import {IFactory} from "../../interfaces/IFactory.sol";
import {IPriceReader} from "../../interfaces/IPriceReader.sol";
import {ISwapper} from "../../interfaces/ISwapper.sol";
import {IStrategy} from "../../interfaces/IStrategy.sol";
import {IFarmingStrategy} from "../../interfaces/IFarmingStrategy.sol";
import {IRevenueRouter} from "../../interfaces/IRevenueRouter.sol";
library StrategyLib {
using SafeERC20 for IERC20;
/// @dev Reward pools may have low liquidity and up to 2% fees
uint internal constant SWAP_REWARDS_PRICE_IMPACT_TOLERANCE = 7_000;
struct ExtractFeesVars {
IPlatform platform;
uint feePlatform;
uint amountPlatform;
}
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);
}
$._rewardsOnBalance = new uint[](len);
}
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,
address[] memory assets_,
uint[] memory amounts_
) external returns (uint[] memory amountsRemaining) {
ExtractFeesVars memory vars =
ExtractFeesVars({platform: IPlatform(platform), feePlatform: 0, amountPlatform: 0});
(vars.feePlatform,,,) = vars.platform.getFees();
try vars.platform.getCustomVaultFee(vault) returns (uint vaultCustomFee) {
if (vaultCustomFee != 0) {
vars.feePlatform = vaultCustomFee;
}
} catch {}
uint len = assets_.length;
amountsRemaining = new uint[](len);
// nosemgrep
for (uint i; i < len; ++i) {
// revenue fee amount of assets_[i]
vars.amountPlatform = amounts_[i] * vars.feePlatform / ConstantsLib.DENOMINATOR;
vars.amountPlatform = Math.min(vars.amountPlatform, balance(assets_[i]));
if (vars.amountPlatform > 0) {
try vars.platform.revenueRouter() returns (address revenueReceiver) {
IERC20(assets_[i]).forceApprove(revenueReceiver, vars.amountPlatform);
IRevenueRouter(revenueReceiver).processFeeAsset(assets_[i], vars.amountPlatform);
} catch {
// can be only in old strategy upgrade tests
}
amountsRemaining[i] = amounts_[i] - vars.amountPlatform;
amountsRemaining[i] = Math.min(amountsRemaining[i], balance(assets_[i]));
}
}
}
function liquidateRewards(
address platform,
address exchangeAsset,
address[] memory rewardAssets_,
uint[] memory rewardAmounts_,
uint customPriceImpactTolerance
) 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,
Math.min(rewardAmounts_[i], balance(rewardAssets_[i])),
customPriceImpactTolerance != 0
? customPriceImpactTolerance
: 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 computeAprInt(uint tvl, int earned, uint duration) public pure returns (int) {
if (tvl == 0 || duration == 0) {
return 0;
}
return earned * int(1e18) * int(ConstantsLib.DENOMINATOR) * int(365) / int(tvl) / int(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 isPositiveAmountInArray(uint[] memory amounts) external pure returns (bool) {
uint len = amounts.length;
for (uint i; i < len; ++i) {
if (amounts[i] != 0) {
return true;
}
}
return false;
}
function swap(address platform, address tokenIn, address tokenOut, uint amount) external returns (uint amountOut) {
uint outBalanceBefore = balance(tokenOut);
ISwapper swapper = ISwapper(IPlatform(platform).swapper());
swapper.swap(tokenIn, tokenOut, amount, 1000);
amountOut = balance(tokenOut) - outBalanceBefore;
}
function swap(
address platform,
address tokenIn,
address tokenOut,
uint amount,
uint priceImpactTolerance
) external returns (uint amountOut) {
uint outBalanceBefore = balance(tokenOut);
ISwapper swapper = ISwapper(IPlatform(platform).swapper());
swapper.swap(tokenIn, tokenOut, amount, priceImpactTolerance);
amountOut = balance(tokenOut) - outBalanceBefore;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IStrategy} from "./IStrategy.sol";
import {IStabilityVault} from "./IStabilityVault.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, IStabilityVault {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
error NotEnoughBalanceToPay();
error FuseTrigger();
error ExceedSlippageExactAsset(address asset, uint mintToUser, uint minToMint);
error NotEnoughAmountToInitSupply(uint mintAmount, uint initialShares);
error StrategyZeroDeposit();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
event HardWorkGas(uint gasUsed, uint gasCost, bool compensated);
event DoHardWorkOnDepositChanged(bool oldValue, bool newValue);
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;
/// @inheritdoc IStabilityVault
bool lastBlockDefenseDisabled;
}
/// @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 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @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);
/// @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 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;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytesSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getStringSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(string[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 reinitialization) 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 Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.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 ERC-165 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 {
/// @inheritdoc IERC165
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;
/// @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
pragma solidity ^0.8.28;
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
interface IRevenueRouter {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
event EpochFlip(uint periodEnded, uint totalStblRevenue);
event AddedUnit(uint unitIndex, UnitType unitType, string name, address feeTreasury);
event UpdatedUnit(uint unitIndex, UnitType unitType, string name, address feeTreasury);
event UnitEpochRevenue(uint periodEnded, string unitName, uint stblRevenue);
event ProcessUnitRevenue(uint unitIndex, uint stblGot);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
error WaitForNewPeriod();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DATA TYPES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @custom:storage-location erc7201:stability.RevenueRouter
struct RevenueRouterStorage {
address stbl;
address xStbl;
address xStaking;
address feeTreasury;
uint xShare;
uint activePeriod;
uint pendingRevenue;
Unit[] units;
address[] aavePools;
EnumerableSet.AddressSet vaultsAccumulated;
}
enum UnitType {
Core,
AaveMarkets,
Assets
}
struct Unit {
UnitType unitType;
string name;
uint pendingRevenue;
address feeTreasury;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GOV ACTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @notice Add new Unit
function addUnit(UnitType unitType, string calldata name, address feeTreasury) external;
/// @notice Update Unit
function updateUnit(uint unitIndex, UnitType unitType, string calldata name, address feeTreasury) external;
/// @notice Setup Aave pool list
function setAavePools(address[] calldata pools) external;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* USER ACTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @notice Update the epoch (period) -- callable once a week at >= Thursday 0 UTC
/// @return newPeriod The new period
function updatePeriod() external returns (uint newPeriod);
/// @notice Process platform fee in form of an asset
function processFeeAsset(address asset, uint amount) external;
/// @notice Process platform fee in form of an vault shares
function processFeeVault(address vault, uint amount) external;
/// @notice Claim unit fees and swap to STBL
function processUnitRevenue(uint unitIndex) external;
/// @notice Claim units fees and swap to STBL
function processUnitsRevenue() external;
/// @notice Withdraw assets from accumulated vaults and swap to STBL
function processAccumulatedVaults(uint maxVaultsForWithdraw) external;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* VIEW FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @notice Show all Units
function units() external view returns (Unit[] memory);
/// @notice The period used for rewarding
/// @return The block.timestamp divided by 1 week in seconds
function getPeriod() external view returns (uint);
/// @notice Current active period
function activePeriod() external view returns (uint);
/// @notice Accumulated STBL amount for next distribution by core unit (vault fees)
function pendingRevenue() external view returns (uint);
/// @notice Accumulated STBL amount for next distribution by unit
function pendingRevenue(uint unitIndex) external view returns (uint);
/// @notice Get Aave pool list to mintToTreasury calls
function aavePools() external view returns (address[] memory);
/// @notice Get vault addresses that contract hold on balance, but not withdrew yet
function vaultsAccumulated() external view returns (address[] memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @notice Base interface of Stability Vault
interface IStabilityVault is IERC20, IERC20Metadata {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
error WaitAFewBlocks();
error ExceedSlippage(uint mintToUser, uint minToMint);
error ExceedMaxSupply(uint maxSupply);
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 MaxSupply(uint maxShares);
event VaultName(string newName);
event VaultSymbol(string newSymbol);
event LastBlockDefenseDisabled(bool isDisabled);
//region --------------------------------------- View functions
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* VIEW FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @notice Underlying assets
function assets() external view returns (address[] memory);
/// @notice Immutable vault type ID
function vaultType() external view returns (string memory);
/// @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);
/// @dev USD price of share with 18 decimals.
/// Not trusted vault share price can be manipulated, used only OFF-CHAIN.
/// @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
/// Not trusted vault share price can be manipulated, used only OFF-CHAIN.
/// @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 Minimum 6 blocks between deposit and withdraw check disabled
function lastBlockDefenseDisabled() external view returns (bool);
/// @return amount Maximum amount that can be withdrawn from the vault for the given account.
/// This is max amount that can be passed to `withdraw` function.
/// The implementation should take into account IStrategy.maxWithdrawAssets
/// @dev It's alias of IStabilityVault.maxWithdraw(account, 0) for backwords compatibility.
function maxWithdraw(address account) external view returns (uint amount);
/// @return amount Maximum amount that can be withdrawn from the vault for the given account.
/// This is max amount that can be passed to `withdraw` function.
/// The implementation should take into account IStrategy.maxWithdrawAssets
/// @param mode 0 - Return amount that can be withdrawn in assets
/// 1 - Return amount that can be withdrawn in underlying
function maxWithdraw(address account, uint mode) external view returns (uint amount);
/// @return maxAmounts Maximum amounts that can be deposited to the vault for the given account.
/// This is max amounts of {assets} that can be passed to `depositAssets` function as {amountsMax}.
/// The implementation should take into account IStrategy.maxDepositAssets
/// Return type(uint).max if there is no limit for the asset.
function maxDeposit(address account) external view returns (uint[] memory maxAmounts);
//endregion --------------------------------------- View functions
//region --------------------------------------- Write functions
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* WRITE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @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 Changing ERC20 name of vault
function setName(string calldata newName) external;
/// @dev Changing ERC20 symbol of vault
function setSymbol(string calldata newSymbol) external;
/// @dev Enable or disable last block check
function setLastBlockDefenseDisabled(bool isDisabled) external;
//endregion --------------------------------------- Write functions
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}{
"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/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false,
"libraries": {
"src/strategies/SiloMerklFarmStrategy.sol": {
"CommonLib": "0xcb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697",
"StrategyLib": "0x13d579335a6bf08ff312087486ee63bae79d2496"
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"name":"AlreadyExist","type":"error"},{"inputs":[],"name":"BadFarm","type":"error"},{"inputs":[],"name":"ETHTransferFailed","type":"error"},{"inputs":[],"name":"IncorrectArrayLength","type":"error"},{"inputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"address[]","name":"expectedAssets_","type":"address[]"}],"name":"IncorrectAssetsList","type":"error"},{"inputs":[],"name":"IncorrectBalance","type":"error"},{"inputs":[],"name":"IncorrectInitParams","type":"error"},{"inputs":[{"internalType":"uint256","name":"ltv","type":"uint256"}],"name":"IncorrectLtv","type":"error"},{"inputs":[],"name":"IncorrectMsgSender","type":"error"},{"inputs":[],"name":"IncorrectStrategyId","type":"error"},{"inputs":[],"name":"IncorrectZeroArgument","type":"error"},{"inputs":[],"name":"InsufficientBalance","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":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"TooLowValue","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":"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"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"","type":"string"}],"name":"SpecificName","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string[]","name":"","type":"string[]"}],"name":"StrategyProtocols","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_MERKL_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":"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":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"distributor","type":"address"},{"internalType":"address[]","name":"tokens","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"bytes32[][]","name":"proofs","type":"bytes32[][]"}],"name":"claimToMultisig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"createdBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"customPriceImpactTolerance","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":"fuseMode","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAssetsProportions","outputs":[{"internalType":"uint256[]","name":"proportions","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getRevenue","outputs":[{"internalType":"address[]","name":"__assets","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","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":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"isReadyForHardWork","outputs":[{"internalType":"bool","name":"isReady","type":"bool"}],"stateMutability":"pure","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":"maxDepositAssets","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxWithdrawAssets","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"maxWithdrawAssets","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"platform","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolTvl","outputs":[{"internalType":"uint256","name":"tvlUsd","type":"uint256"}],"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":"protocols","outputs":[{"internalType":"string[]","name":"","type":"string[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"refreshFarmingAssets","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"priceImpactTolerance","type":"uint256"}],"name":"setCustomPriceImpactTolerance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string[]","name":"protocols_","type":"string[]"}],"name":"setProtocols","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"specific","type":"string"}],"name":"setSpecificName","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":[{"internalType":"address","name":"distributor","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"toggleDistributorUserOperator","outputs":[],"stateMutability":"nonpayable","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
6080604052348015600e575f5ffd5b5060156019565b60c9565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff161560685760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b039081161460c65780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b6157ad806100d65f395ff3fe608060405234801561000f575f5ffd5b506004361061034d575f3560e01c806371a97305116101c9578063b6c8cdef116100fe578063f1faf0501161009e578063f985b0bc11610079578063f985b0bc146106d2578063fbfa77cf146106e5578063fdff667c146106ed578063ffa1ad741461059f575f5ffd5b8063f1faf050146106ad578063f55dd6c1146106b5578063f815c4ff146106ca575f5ffd5b8063c1ec4eb4116100d9578063c1ec4eb414610650578063ead0bc4714610663578063ecfa9b9114610676578063f198f5f71461069a575f5ffd5b8063b6c8cdef146105c3578063b9f5be411461062a578063bd5a74681461063d575f5ffd5b8063936725ec11610169578063a2b7722c11610144578063a2b7722c146105dc578063aa47f4e1146105ef578063aefb0751146105f7578063b600585a14610617575f5ffd5b8063936725ec1461059f5780639736374e146105c357806399f428cf146105c9575f5ffd5b806380e7ac7c116101a457806380e7ac7c1461058157806383ecf6531461058857806389816e30146105905780638c3aefa714610598575f5ffd5b806371a97305146105645780637284e4161461057957806374bac42914610581575f5ffd5b806341affeb81161029f57806350f4e4191161023f57806367cf905a1161021a57806367cf905a1461052b57806367fde573146105335780636d9894391461053b5780636f307dc31461055c575f5ffd5b806350f4e419146104df57806359498ab7146104ff5780635b0f088a14610507575f5ffd5b806348d7d9eb1161027a57806348d7d9eb146104aa5780634bde38c8146104bc5780634d8f1277146104c45780634fa5d854146104d7575f5ffd5b806341affeb8146104645780634593144c146104775780634875c9681461047f575f5ffd5b806320208ad81161030a5780632d433b28116102e55780632d433b28146104295780632ddbd13a1461044c578063394f52321461045457806341760fe61461045c575f5ffd5b806320208ad8146103cf578063278de000146103e45780632a8ba293146103f8575f5ffd5b806301ffc9a7146103515780630c56ae3b1461037957806313e63180146103935780631639ba98146103a9578063190024e0146103b15780631ec71e05146103b9575b5f5ffd5b61036461035f3660046140d6565b6106f5565b60405190151581526020015b60405180910390f35b5f5b6040516001600160a01b039091168152602001610370565b61039b610723565b604051908152602001610370565b61039b610735565b61039b610747565b6103c16107e8565b60405161037092919061412b565b6103e26103dd3660046141a2565b610b07565b005b5f5160206157585f395f51905f525461039b565b61041c604051806040016040528060058152602001640c4b8ccb8d60da1b81525081565b6040516103709190614250565b61043c610437366004614262565b610e67565b604051610370949392919061434a565b61039b610eb0565b6103e2610ec2565b61039b610f55565b6103e2610472366004614557565b610f67565b61039b611367565b60408051808201909152600f81526e53696c6f204d65726b6c204661726d60881b602082015261041c565b6060805b604051610370929190614644565b61037b61139a565b6103e26104d23660046146e4565b6113c9565b6103e261142e565b6104f26104ed366004614793565b611863565b60405161037091906147e9565b6104ae611880565b61041c604051806040016040528060058152602001640322e362e360dc1b81525081565b6104f2611912565b6103e261195e565b61054e6105493660046147fb565b611988565b60405161037092919061485e565b61037b611a8d565b61056c611aa8565b604051610370919061487f565b61041c611b11565b6001610364565b6104f2611b2d565b61039b611b38565b60606104f2565b61041c60405180604001604052806005815260200164312e302e3160d81b81525081565b5f610364565b6103e26105d7366004614891565b611d74565b61039b6105ea3660046148bf565b611d8a565b61056c611dc4565b6040805180820190915260048152634175746f60e01b602082015261041c565b61054e6106253660046147fb565b611e31565b6104f26106383660046148f0565b611f1e565b6103e261064b3660046148f0565b611f31565b6103e261065e366004614907565b611f4c565b6104f26106713660046148f0565b611f9d565b61041c604051806040016040528060058152602001640312e312e360dc1b81525081565b6103e26106a8366004614938565b612062565b61039b6120ca565b6106bd6120dc565b6040516103709190614964565b61039b6121b9565b6104f26106e0366004614976565b6121cb565b61037b612274565b6106bd61228c565b5f6106ff826122fe565b8061070e575061070e8261231e565b8061071d575061071d826122fe565b92915050565b5f61072c612342565b60020154905090565b5f61073e612342565b60090154905090565b6040805161d39560e81b60208201525f6023820181905282516006818403018152602683019384905263bfe370d960e01b9093529173cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979163bfe370d9916107a491602a01614250565b602060405180830381865af41580156107bf573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107e391906149a1565b905090565b60605f5f6107f4612342565b600c018054610802906149b8565b80601f016020809104026020016040519081016040528092919081815260200182805461082e906149b8565b80156108795780601f1061085057610100808354040283529160200191610879565b820191905f5260205f20905b81548152906001019060200180831161085c57829003601f168201915b5050505050905080515f146108915792600192509050565b5f61089a612366565b90505f6108a68261238d565b90505f816001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108e5573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061090991906149fb565b90505f5f826001600160a01b031663aecc90cb6040518163ffffffff1660e01b81526004016040805180830381865afa158015610948573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061096c9190614a16565b915091505f826001600160a01b0316856001600160a01b0316146109905782610992565b815b9050806001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109d0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109f491906149fb565b6001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015610a2e573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610a559190810190614a90565b73cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee69763be59b507610a776123b3565b6040518263ffffffff1660e01b8152600401610a9591815260200190565b5f60405180830381865af4158015610aaf573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610ad69190810190614a90565b604051602001610ae7929190614ad8565b604051602081830303815290604052600198509850505050505050509091565b610b0f612486565b5f610b1861139a565b6001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b53573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b7791906149fb565b9050855f816001600160401b03811115610b9357610b936143cb565b604051908082528060200260200182016040528015610bbc578160200160208202803683370190505b5090505f826001600160401b03811115610bd857610bd86143cb565b604051908082528060200260200182016040528015610c01578160200160208202803683370190505b5090505f5b83811015610cee578a8a82818110610c2057610c20614af8565b9050602002016020810190610c359190614262565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015610c79573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c9d91906149a1565b828281518110610caf57610caf614af8565b60200260200101818152505030838281518110610cce57610cce614af8565b6001600160a01b0390921660209283029190910190910152600101610c06565b506040516301c7ba5760e61b81526001600160a01b038c16906371ee95c090610d279085908e908e908e908e908e908e90600401614b3c565b5f604051808303815f87803b158015610d3e575f5ffd5b505af1158015610d50573d5f5f3e3d5ffd5b505050505f5b83811015610e59575f828281518110610d7157610d71614af8565b60200260200101518c8c84818110610d8b57610d8b614af8565b9050602002016020810190610da09190614262565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015610de4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0891906149a1565b610e129190614c64565b9050610e5086828e8e86818110610e2b57610e2b614af8565b9050602002016020810190610e409190614262565b6001600160a01b03169190612515565b50600101610d56565b505050505050505050505050565b606080606080610ea1856040518060400160405280600f81526020016e53696c6f204d65726b6c204661726d60881b8152506125746127db565b93509350935093509193509193565b5f610eb9612342565b60010154905090565b610eca612486565b7313d579335a6bf08ff312087486ee63bae79d249663fede401f5f5160206157585f395f51905f52610efa61139a565b6040516001600160e01b031960e085901b16815260048101929092526001600160a01b031660248201526044015f6040518083038186803b158015610f3d575f5ffd5b505af4158015610f4f573d5f5f3e3d5ffd5b50505050565b5f610f5e612342565b600a0154905090565b5f610f70612b69565b805490915060ff600160401b82041615906001600160401b03165f81158015610f965750825b90505f826001600160401b03166001148015610fb15750303b155b905081158015610fbf575080155b15610fdd5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561100757845460ff60401b1916600160401b1785555b8751600214158061101a57508651600114155b806110255750855115155b15611043576040516363cf6b6160e01b815260040160405180910390fd5b5f611080895f8151811061105957611059614af8565b6020026020010151895f8151811061107357611073614af8565b6020026020010151612b91565b9050806080015151600314158061109d57508060a0015151600114155b806110ac575060c08101515115155b156110ca576040516325b769d160e11b815260040160405180910390fd5b6040805160018082528183019092525f91602080830190803683370190505090505f6110f58361238d565b9050806001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611133573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061115791906149fb565b825f8151811061116957611169614af8565b60200260200101906001600160a01b031690816001600160a01b0316815250506111f18b5f8151811061119e5761119e614af8565b60200260200101516040518060400160405280600f81526020016e53696c6f204d65726b6c204661726d60881b8152508d6001815181106111e1576111e1614af8565b6020026020010151855f5f612c6e565b61122d8b5f8151811061120657611206614af8565b60200260200101518b5f8151811061122057611220614af8565b6020026020010151612d12565b611265815f19845f8151811061124557611245614af8565b60200260200101516001600160a01b0316612d969092919063ffffffff16565b8260a001515f8151811061127b5761127b614af8565b60200260200101516001146112e35760405162461bcd60e51b815260206004820152602360248201527f4f6e6c7920436f6c6c61746572616c20737570706f727465642c2073656520236044820152620cce4d60ea1b60648201526084015b60405180910390fd5b5f6112ed84612e25565b90506001600160a01b03811615611313576113136001600160a01b038316825f19612d96565b50505050831561135d57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050565b5f6107e361139660017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f1614c64565b5490565b5f6107e361139660017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d6614c64565b6113d1612486565b5f6113da612342565b82519091506113f290600b8301906020850190613f78565b507fd319c6758f17094777edee94fbe0651a574464c07a5167e481d19cc2e0acf133826040516114229190614964565b60405180910390a15050565b611436612e3d565b61143e612e6e565b5f611447612342565b805460408051637299470360e11b815281519394506001600160a01b03909216925f92849263e5328e06926004808401938290030181865afa15801561148f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b39190614c86565b509050801561185e575f6114c561139a565b60088501549091505f8080806114d9612eeb565b93509350935093505f6114e95f90565b6115d45761151185878151811061150257611502614af8565b60200260200101518484613455565b84878151811061152357611523614af8565b602002602001018181516115379190614cb0565b9052506040516308dc79a160e01b81525f907313d579335a6bf08ff312087486ee63bae79d2496906308dc79a190611579908b908e908b908b90600401614cc3565b5f60405180830381865af4158015611593573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526115ba9190810190614d66565b60018c81015493509091506115cd613461565b50506117e9565b604051633596603f60e01b81527313d579335a6bf08ff312087486ee63bae79d249690633596603f9061160b9087906004016147e9565b602060405180830381865af4158015611626573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061164a9190614d97565b156116af576040516336ac731760e11b81526001600160a01b038a1690636d58e62e9061167d9088908890600401614644565b5f604051808303815f87803b158015611694575f5ffd5b505af11580156116a6573d5f5f3e3d5ffd5b505050506117cb565b5f6116b8611880565b9150505f86516001600160401b038111156116d5576116d56143cb565b6040519080825280602002602001820160405280156116fe578160200160208202803683370190505b50905060076301e133808d60020154426117189190614c64565b845f8151811061172a5761172a614af8565b602002602001015161173c9190614db0565b6117469190614dc7565b6117509190614dc7565b815f8151811061176257611762614af8565b60209081029190910101526040516336ac731760e11b81526001600160a01b038c1690636d58e62e9061179b908a908590600401614644565b5f604051808303815f87803b1580156117b2575f5ffd5b505af11580156117c4573d5f5f3e3d5ffd5b5050505050505b6117e0855f8151811061150257611502614af8565b506117e9613461565b60405163640f244560e01b81527313d579335a6bf08ff312087486ee63bae79d24969063640f24459061182a908d908b908a908a908f908990600401614de6565b5f6040518083038186803b158015611840575f5ffd5b505af4158015611852573d5f5f3e3d5ffd5b50505050505050505050505b505050565b606061186d612e3d565b6118788484846136b5565b949350505050565b60608061188b6137cf565b604051633f8b51a560e21b815291935091507313d579335a6bf08ff312087486ee63bae79d24969063fe2d4694906118c99085908590600401614644565b5f60405180830381865af41580156118e3573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261190a9190810190614e9b565b915091509091565b60408051600180825281830190925260609160208083019080368337019050509050670de0b6b3a7640000815f8151811061194f5761194f614af8565b60200260200101818152505090565b611966613893565b611977611971610eb0565b306139ad565b506001611982612342565b600a0155565b60605f835160011480156119d4575061199f612342565b6006015484516001600160a01b039091169085905f906119c1576119c1614af8565b60200260200101516001600160a01b0316145b8015611a0b57505f6001600160a01b0316845f815181106119f7576119f7614af8565b60200260200101516001600160a01b031614155b15611a77578251600114611a3257604051630ef9926760e21b815260040160405180910390fd5b825f81518110611a4457611a44614af8565b60200260200101519050611a70835f81518110611a6357611a63614af8565b6020026020010151613a1f565b9150611a86565b611a818484613a27565b915091505b9250929050565b5f611a96612342565b600601546001600160a01b0316919050565b6060611ab2612342565b600501805480602002602001604051908101604052809291908181526020018280548015611b0757602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311611ae9575b5050505050905090565b60605f611b1c612366565b9050611b2781612574565b91505090565b60606107e35f611f9d565b5f5f611b42612366565b90505f611b4e8261238d565b90505f816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b8d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bb191906149fb565b90505f611bbc61139a565b6001600160a01b03166349b5fdb46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bf7573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c1b91906149fb565b6040516341976e0960e01b81526001600160a01b0384811660048301529192505f918316906341976e09906024016040805180830381865afa158015611c63573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c879190614c86565b509050826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cc6573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611cea9190614ef4565b611cf590600a614ff7565b81856001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d32573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d5691906149a1565b611d609190614db0565b611d6a9190614dc7565b9550505050505090565b611d7c612e3d565b611d868282613a34565b5050565b5f611d93612e3d565b5f611d9c612342565b905080600201545f03611db0574260028201555b611dbb836001613abc565b9150505b919050565b60605f5160206157585f395f51905f52600101805480602002602001604051908101604052809291908181526020018280548015611b0757602002820191905f5260205f209081546001600160a01b03168152600190910190602001808311611ae9575050505050905090565b60605f83516001148015611e7d5750611e48612342565b6006015484516001600160a01b039091169085905f90611e6a57611e6a614af8565b60200260200101516001600160a01b0316145b8015611eb457505f6001600160a01b0316845f81518110611ea057611ea0614af8565b60200260200101516001600160a01b031614155b15611f14578251600114611edb57604051630ef9926760e21b815260040160405180910390fd5b825f81518110611eed57611eed614af8565b60200260200101519050611a70835f81518110611f0c57611f0c614af8565b506060919050565b611a818484613b96565b6060611f28612e3d565b61071d82613ba2565b611f39612486565b5f611f42612342565b6009019190915550565b611f54612486565b5f611f5d612342565b9050600c8101611f6d8382615050565b507fd65900dd44764cfc9d7d6f6a36f82c15f38955a604922fa324ed9516e26e186f826040516114229190614250565b60605f611fa8612366565b90505f611fb48261238d565b604080516001808252818301909252919250602080830190803683370190505060405163ce96cb7760e01b81523060048201529093506001600160a01b0382169063ce96cb7790602401602060405180830381865afa158015612019573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061203d91906149a1565b835f8151811061204f5761204f614af8565b6020026020010181815250505050919050565b61206a612486565b60405163bdac7ca360e01b81523060048201526001600160a01b03828116602483015283169063bdac7ca3906044015f604051808303815f87803b1580156120b0575f5ffd5b505af11580156120c2573d5f5f3e3d5ffd5b505050505050565b5f6120d3612342565b60040154905090565b60606120e6612342565b600b01805480602002602001604051908101604052809291908181526020015f905b828210156121b0578382905f5260205f20018054612125906149b8565b80601f0160208091040260200160405190810160405280929190818152602001828054612151906149b8565b801561219c5780601f106121735761010080835404028352916020019161219c565b820191905f5260205f20905b81548152906001019060200180831161217f57829003601f168201915b505050505081526020019060010190612108565b50505050905090565b5f6121c2612342565b60030154905090565b60606121d5612e3d565b7313d579335a6bf08ff312087486ee63bae79d24966325567aef6121f7612342565b6040516001600160e01b031960e084901b168152600481019190915260248101879052604481018690526001600160a01b03851660648201526084015f60405180830381865af415801561224d573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526118789190810190614d66565b5f61227d612342565b546001600160a01b0316919050565b604080516001808252818301909252606091816020015b60608152602001906001900390816122a35790505090506040518060400160405280600b81526020016a436f6d706f756e64696e6760a81b815250815f815181106122f0576122f0614af8565b602002602001018190525090565b5f6001600160e01b031982166396cf43c560e01b148061071d575061071d825b5f6001600160e01b0319821663d1b87f2f60e01b148061071d575061071d82613bad565b7fb14b643f49bed6a2c6693bbd50f68dc950245db265c66acadbfa51ccc8c3ba0090565b61236e613fcc565b6107e361237961139a565b5f5160206157585f395f51905f5254612b91565b5f81608001515f815181106123a4576123a4614af8565b60200260200101519050919050565b5f5f6123bd612366565b90506123c88161238d565b6001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa158015612403573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061242791906149fb565b6001600160a01b031663189e17e46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612462573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b2791906149a1565b61248e61139a565b6040516336b87bd760e11b81523360048201526001600160a01b039190911690636d70f7ae90602401602060405180830381865afa1580156124d2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124f69190614d97565b61251357604051631f0853c160e21b815260040160405180910390fd5b565b6040516001600160a01b0383811660248301526044820183905261185e91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050613bd1565b606073cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697631dfab92873cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee69763fbcadbe985606001516040518263ffffffff1660e01b81526004016125cb919061487f565b5f60405180830381865af41580156125e5573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261260c919081019061510a565b6040518263ffffffff1660e01b815260040161262891906151ae565b5f60405180830381865af4158015612642573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526126699190810190614a90565b6126728361238d565b6001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156126ad573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126d191906149fb565b6001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa15801561270b573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526127329190810190614a90565b73cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee69763be59b5076127546123b3565b6040518263ffffffff1660e01b815260040161277291815260200190565b5f60405180830381865af415801561278c573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526127b39190810190614a90565b6040516020016127c59392919061522d565b6040516020818303038152906040529050919050565b60608080805f60405190808252806020026020018201604052801561280a578160200160208202803683370190505b50604080515f808252602082019092529194505090505f876001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa15801561285d573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061288191906149fb565b6001600160a01b031663871fd6826040518163ffffffff1660e01b81526004015f60405180830381865afa1580156128bb573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526128e29190810190615413565b80519091505f805b828110156129b2575f84828151811061290557612905614af8565b60200260200101519050805f01515f148015612998575060408082015190516310d24b2160e11b815273cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697916321a496429161295991908f906004016154b7565b602060405180830381865af4158015612974573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129989190614d97565b156129a9576129a6836154db565b92505b506001016128ea565b50806001600160401b038111156129cb576129cb6143cb565b6040519080825280602002602001820160405280156129fe57816020015b60608152602001906001900390816129e95790505b509650806001600160401b03811115612a1957612a196143cb565b604051908082528060200260200182016040528015612a42578160200160208202803683370190505b5094505f90505f5b82811015612b5c575f848281518110612a6557612a65614af8565b60200260200101519050805f01515f148015612af8575060408082015190516310d24b2160e11b815273cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697916321a4964291612ab991908f906004016154b7565b602060405180830381865af4158015612ad4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612af89190614d97565b15612b535781878481518110612b1057612b10614af8565b602002602001018181525050612b29818b63ffffffff16565b898481518110612b3b57612b3b614af8565b602002602001018190525082612b50906154db565b92505b50600101612a4a565b5050505093509350935093565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0061071d565b612b99613fcc565b826001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015612bd5573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bf991906149fb565b6001600160a01b031663538a85a1836040518263ffffffff1660e01b8152600401612c2691815260200190565b5f60405180830381865afa158015612c40573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612c6791908101906154f3565b9392505050565b612c76613c3d565b612c7f86613c62565b5f612c88612342565b600881018390556006810180546001600160a01b0319166001600160a01b03861617905584519091508690869086908690869060078701905f9088908290612cd990600584019060208a0190614010565b5081546001600160a01b03808a166101009390930a9283029202191617905550612d038682615050565b50505050505050505050505050565b612d1a613c3d565b7313d579335a6bf08ff312087486ee63bae79d2496634ab3b02f5f5160206157585f395f51905f52612d4a612342565b60070185856040518563ffffffff1660e01b8152600401612d6e9493929190615524565b5f6040518083038186803b158015612d84575f5ffd5b505af41580156120c2573d5f5f3e3d5ffd5b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052612de78482613dbf565b610f4f576040516001600160a01b0384811660248301525f6044830152612e1b91869182169063095ea7b390606401612542565b610f4f8482613bd1565b5f81608001516002815181106123a4576123a4614af8565b612e45612342565b546001600160a01b03163314612513576040516362df054560e01b815260040160405180910390fd5b306001600160a01b03166374bac4296040518163ffffffff1660e01b8152600401602060405180830381865afa158015612eaa573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ece9190614d97565b612513576040516309ea311f60e11b815260040160405180910390fd5b6060806060805f612efa612342565b90505f5160206157585f395f51905f52612f12611aa8565b955085516001600160401b03811115612f2d57612f2d6143cb565b604051908082528060200260200182016040528015612f56578160200160208202803683370190505b5060018201805460408051602080840282018101909252828152939850830182828015612faa57602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311612f8c575b5050835193975083925050506001600160401b03811115612fcd57612fcd6143cb565b604051908082528060200260200182016040528015612ff6578160200160208202803683370190505b5093505f613002612366565b90505f61300e8261238d565b60018601546040516370a0823160e01b8152306004820152919250906001600160a01b038316906307a2d13a9082906370a0823190602401602060405180830381865afa158015613061573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061308591906149a1565b6040518263ffffffff1660e01b81526004016130a391815260200190565b602060405180830381865afa1580156130be573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130e291906149a1565b6130ec9190614c64565b885f815181106130fe576130fe614af8565b6020026020010181815250505f61311483612e25565b90506001600160a01b0381161561319057604051633bd73ee360e21b81523060048201526001600160a01b0382169063ef5cfb8c906024015f604051808303815f875af1158015613167573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261318e91908101906155c5565b505b5f61319a84613e08565b90505f6001600160a01b0382166131b1575f613211565b816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156131ed573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061321191906149fb565b90505f5b86811015613446577313d579335a6bf08ff312087486ee63bae79d249663e3d670d78c838151811061324957613249614af8565b60200260200101516040518263ffffffff1660e01b815260040161327c91906001600160a01b0391909116815260200190565b602060405180830381865af4158015613297573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132bb91906149a1565b8a82815181106132cd576132cd614af8565b602002602001018181525050816001600160a01b03168b82815181106132f5576132f5614af8565b60200260200101516001600160a01b031614801561331b57506001600160a01b03831615155b1561343e5760405163e3d670d760e01b81526001600160a01b03841660048201525f907313d579335a6bf08ff312087486ee63bae79d24969063e3d670d790602401602060405180830381865af4158015613378573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061339c91906149a1565b9050801561343c576040516314e726f160e31b8152600481018290525f60248201526001600160a01b0385169063a7393788906044016020604051808303815f875af11580156133ee573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061341291906149a1565b8b838151811061342457613424614af8565b602002602001018181516134389190614cb0565b9052505b505b600101613215565b50505050505050505090919293565b5f611878848484613e20565b5f61346a611aa8565b80519091505f816001600160401b03811115613488576134886143cb565b6040519080825280602002602001820160405280156134b1578160200160208202803683370190505b5090505f5f5b838110156135a8577313d579335a6bf08ff312087486ee63bae79d249663e3d670d78683815181106134eb576134eb614af8565b60200260200101516040518263ffffffff1660e01b815260040161351e91906001600160a01b0391909116815260200190565b602060405180830381865af4158015613539573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061355d91906149a1565b83828151811061356f5761356f614af8565b60200260200101818152505082818151811061358d5761358d614af8565b60200260200101515f146135a057600191505b6001016134b7565b505f6135b2612366565b90505f6135be8261238d565b90505f6135c9612342565b6040516370a0823160e01b81523060048201529091506001600160a01b038316906307a2d13a9082906370a0823190602401602060405180830381865afa158015613616573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061363a91906149a1565b6040518263ffffffff1660e01b815260040161365891815260200190565b602060405180830381865afa158015613673573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061369791906149a1565b600182015583156136ac5761135d855f613abc565b50505050505050565b60605f6136c0612366565b90505f6136cc8261238d565b9050846001600160a01b03851630036136ed57806136e981615684565b9150505b604051635c19be1560e11b81526001600160a01b0383169063b8337c2a90613720908490899030906001906004016156b9565b6020604051808303815f875af115801561373c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061376091906149a1565b50604080516001808252818301909252906020808301908036833701905050935085845f8151811061379457613794614af8565b6020026020010181815250505f6137a9612342565b905086816001015f8282546137be9190614c64565b909155509498975050505050505050565b6060805f6137db612342565b6005810180546040805160208084028201810190925282815293945083018282801561382e57602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311613810575b509396506001935061383f92505050565b604051908082528060200260200182016040528015613868578160200160208202803683370190505b5091508060010154825f8151811061388257613882614af8565b602002602001018181525050509091565b5f61389c61139a565b9050336001600160a01b0316816001600160a01b0316635aa6e6756040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138e4573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061390891906149fb565b6001600160a01b0316148061398d5750336001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561395e573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061398291906149fb565b6001600160a01b0316145b6139aa576040516354299b6f60e01b815260040160405180910390fd5b50565b60605f6139b8612342565b905061187881600501805480602002602001604051908101604052809291908181526020018280548015613a1357602002820191905f5260205f20905b81546001600160a01b031681526001909101906020018083116139f5575b505050505085856136b5565b60608061071d565b60605f611a818484613b96565b5f613a3d612342565b600601546001600160a01b031614613a7c576040518060400160405280600f81526020016e1b9bdd081a5b5c1b195b595b9d1959608a1b815250613aa3565b6040518060400160405280600d81526020016c6e6f20756e6465726c79696e6760981b8152505b60405162461bcd60e51b81526004016112da9190614250565b5f5f613ac6612366565b90505f613ad1612342565b90505f613add8361238d565b9050855f81518110613af157613af1614af8565b60200260200101519350835f14613b8d5760405163b7ec8d4b60e01b81526001600160a01b0382169063b7ec8d4b90613b3390879030906001906004016156e4565b6020604051808303815f875af1158015613b4f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b7391906149a1565b5083826001015f828254613b879190614cb0565b90915550505b50505092915050565b60605f611a8183613ead565b60605f613a3d612342565b5f6001600160e01b03198216637a2a253160e01b148061071d575061071d82613f2b565b5f5f60205f8451602086015f885af180613bf0576040513d5f823e3d81fd5b50505f513d91508115613c07578060011415613c14565b6001600160a01b0384163b155b15610f4f57604051635274afe760e01b81526001600160a01b03851660048201526024016112da565b613c45613f5f565b61251357604051631afcd79f60e31b815260040160405180910390fd5b613c6a613c3d565b6001600160a01b03811615801590613cf357505f6001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613cc3573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ce791906149fb565b6001600160a01b031614155b613d10576040516371c42ac360e01b815260040160405180910390fd5b613d43613d3e60017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d6614c64565b829055565b613d7543613d7260017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f1614c64565b55565b604080516001600160a01b0383168152426020820152438183015290517f1a2dd071001ebf6e03174e3df5b305795a4ad5d41d8fdb9ba41dbbe2367134269181900360600190a150565b5f5f5f5f60205f8651602088015f8a5af192503d91505f519050828015613dfe57508115613df05780600114613dfe565b5f866001600160a01b03163b115b9695505050505050565b5f81608001516001815181106123a4576123a4614af8565b5f7313d579335a6bf08ff312087486ee63bae79d249663b9f637cd613e4361139a565b868686613e4e610735565b6040518663ffffffff1660e01b8152600401613e6e959493929190615707565b602060405180830381865af4158015613e89573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061187891906149a1565b6040805160018082528183019092526060915f919060208083019080368337019050509150825f81518110613ee457613ee4614af8565b6020026020010151825f81518110613efe57613efe614af8565b602002602001018181525050815f81518110613f1c57613f1c614af8565b60200260200101519050915091565b5f6001600160e01b03198216630f1ec81f60e41b148061071d57506301ffc9a760e01b6001600160e01b031983161461071d565b5f613f68612b69565b54600160401b900460ff16919050565b828054828255905f5260205f20908101928215613fbc579160200282015b82811115613fbc5782518290613fac9082615050565b5091602001919060010190613f96565b50613fc892915061406f565b5090565b6040518060e001604052805f81526020015f6001600160a01b0316815260200160608152602001606081526020016060815260200160608152602001606081525090565b828054828255905f5260205f20908101928215614063579160200282015b8281111561406357825182546001600160a01b0319166001600160a01b0390911617825560209092019160019091019061402e565b50613fc892915061408b565b80821115613fc8575f614082828261409f565b5060010161406f565b5b80821115613fc8575f815560010161408c565b5080546140ab906149b8565b5f825580601f106140ba575050565b601f0160209004905f5260205f20908101906139aa919061408b565b5f602082840312156140e6575f5ffd5b81356001600160e01b031981168114612c67575f5ffd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b604081525f61413d60408301856140fd565b905082151560208301529392505050565b6001600160a01b03811681146139aa575f5ffd5b5f5f83601f840112614172575f5ffd5b5081356001600160401b03811115614188575f5ffd5b6020830191508360208260051b8501011115611a86575f5ffd5b5f5f5f5f5f5f5f6080888a0312156141b8575f5ffd5b87356141c38161414e565b965060208801356001600160401b038111156141dd575f5ffd5b6141e98a828b01614162565b90975095505060408801356001600160401b03811115614207575f5ffd5b6142138a828b01614162565b90955093505060608801356001600160401b03811115614231575f5ffd5b61423d8a828b01614162565b989b979a50959850939692959293505050565b602081525f612c6760208301846140fd565b5f60208284031215614272575f5ffd5b8135612c678161414e565b5f82825180855260208501945060208160051b830101602085015f5b838110156142cb57601f198584030188526142b58383516140fd565b6020988901989093509190910190600101614299565b50909695505050505050565b5f8151808452602084019350602083015f5b828110156143105781516001600160a01b03168652602095860195909101906001016142e9565b5093949350505050565b5f8151808452602084019350602083015f5b8281101561431057815186526020958601959091019060010161432c565b608081525f61435c608083018761427d565b828103602084015261436e81876142d7565b90508281036040840152614382818661431a565b8381036060850152845180825260208087019350909101905f5b818110156143bd57835160020b83526020938401939092019160010161439c565b509098975050505050505050565b634e487b7160e01b5f52604160045260245ffd5b60405160e081016001600160401b0381118282101715614401576144016143cb565b60405290565b604051606081016001600160401b0381118282101715614401576144016143cb565b604051601f8201601f191681016001600160401b0381118282101715614451576144516143cb565b604052919050565b5f6001600160401b03821115614471576144716143cb565b5060051b60200190565b5f82601f83011261448a575f5ffd5b813561449d61449882614459565b614429565b8082825260208201915060208360051b8601019250858311156144be575f5ffd5b602085015b838110156144e45780356144d68161414e565b8352602092830192016144c3565b5095945050505050565b5f82601f8301126144fd575f5ffd5b813561450b61449882614459565b8082825260208201915060208360051b86010192508583111561452c575f5ffd5b602085015b838110156144e4578035835260209283019201614531565b8060020b81146139aa575f5ffd5b5f5f5f60608486031215614569575f5ffd5b83356001600160401b0381111561457e575f5ffd5b61458a8682870161447b565b93505060208401356001600160401b038111156145a5575f5ffd5b6145b1868287016144ee565b92505060408401356001600160401b038111156145cc575f5ffd5b8401601f810186136145dc575f5ffd5b80356145ea61449882614459565b8082825260208201915060208360051b85010192508883111561460b575f5ffd5b6020840193505b8284101561463657833561462581614549565b825260209384019390910190614612565b809450505050509250925092565b604081525f61465660408301856142d7565b8281036020840152614668818561431a565b95945050505050565b5f6001600160401b03821115614689576146896143cb565b50601f01601f191660200190565b5f82601f8301126146a6575f5ffd5b81356146b461449882614671565b8181528460208386010111156146c8575f5ffd5b816020850160208301375f918101602001919091529392505050565b5f602082840312156146f4575f5ffd5b81356001600160401b03811115614709575f5ffd5b8201601f81018413614719575f5ffd5b803561472761449882614459565b8082825260208201915060208360051b850101925086831115614748575f5ffd5b602084015b838110156147885780356001600160401b0381111561476a575f5ffd5b61477989602083890101614697565b8452506020928301920161474d565b509695505050505050565b5f5f5f606084860312156147a5575f5ffd5b83356001600160401b038111156147ba575f5ffd5b6147c68682870161447b565b9350506020840135915060408401356147de8161414e565b809150509250925092565b602081525f612c67602083018461431a565b5f5f6040838503121561480c575f5ffd5b82356001600160401b03811115614821575f5ffd5b61482d8582860161447b565b92505060208301356001600160401b03811115614848575f5ffd5b614854858286016144ee565b9150509250929050565b604081525f614870604083018561431a565b90508260208301529392505050565b602081525f612c6760208301846142d7565b5f5f604083850312156148a2575f5ffd5b8235915060208301356148b48161414e565b809150509250929050565b5f602082840312156148cf575f5ffd5b81356001600160401b038111156148e4575f5ffd5b611878848285016144ee565b5f60208284031215614900575f5ffd5b5035919050565b5f60208284031215614917575f5ffd5b81356001600160401b0381111561492c575f5ffd5b61187884828501614697565b5f5f60408385031215614949575f5ffd5b82356149548161414e565b915060208301356148b48161414e565b602081525f612c67602083018461427d565b5f5f5f60608486031215614988575f5ffd5b833592506020840135915060408401356147de8161414e565b5f602082840312156149b1575f5ffd5b5051919050565b600181811c908216806149cc57607f821691505b6020821081036149ea57634e487b7160e01b5f52602260045260245ffd5b50919050565b8051611dbf8161414e565b5f60208284031215614a0b575f5ffd5b8151612c678161414e565b5f5f60408385031215614a27575f5ffd5b8251614a328161414e565b60208401519092506148b48161414e565b5f82601f830112614a52575f5ffd5b8151614a6061449882614671565b818152846020838601011115614a74575f5ffd5b8160208501602083015e5f918101602001919091529392505050565b5f60208284031215614aa0575f5ffd5b81516001600160401b03811115614ab5575f5ffd5b61187884828501614a43565b5f81518060208401855e5f93019283525090919050565b5f614ae38285614ac1565b61016160f51b81526146686002820185614ac1565b634e487b7160e01b5f52603260045260245ffd5b8183525f6001600160fb1b03831115614b23575f5ffd5b8260051b80836020870137939093016020019392505050565b608081525f614b4e608083018a6142d7565b8281036020808501919091528882528991015f5b89811015614b92578235614b758161414e565b6001600160a01b0316825260209283019290910190600101614b62565b508381036040850152614ba681888a614b0c565b8481036060860152858152915050602080820190600586901b830101865f36829003601e19015b88821015614c3d57858403601f190185528235818112614beb575f5ffd5b8a016020810190356001600160401b03811115614c06575f5ffd5b8060051b3603821315614c17575f5ffd5b614c22868284614b0c565b95505050602083019250602085019450600182019150614bcd565b50919d9c50505050505050505050505050565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561071d5761071d614c50565b80518015158114611dbf575f5ffd5b5f5f60408385031215614c97575f5ffd5b82519150614ca760208401614c77565b90509250929050565b8082018082111561071d5761071d614c50565b6001600160a01b038581168252841660208201526080604082018190525f90614cee908301856142d7565b8281036060840152614d00818561431a565b979650505050505050565b5f82601f830112614d1a575f5ffd5b8151614d2861449882614459565b8082825260208201915060208360051b860101925085831115614d49575f5ffd5b602085015b838110156144e4578051835260209283019201614d4e565b5f60208284031215614d76575f5ffd5b81516001600160401b03811115614d8b575f5ffd5b61187884828501614d0b565b5f60208284031215614da7575f5ffd5b612c6782614c77565b808202811582820484141761071d5761071d614c50565b5f82614de157634e487b7160e01b5f52601260045260245ffd5b500490565b8681526001600160a01b038616602082015260c0604082018190525f90614e0f908301876142d7565b8281036060840152614e21818761431a565b6080840195909552505060a00152949350505050565b5f82601f830112614e46575f5ffd5b8151614e5461449882614459565b8082825260208201915060208360051b860101925085831115614e75575f5ffd5b602085015b838110156144e4578051614e8d8161414e565b835260209283019201614e7a565b5f5f60408385031215614eac575f5ffd5b82516001600160401b03811115614ec1575f5ffd5b614ecd85828601614e37565b92505060208301516001600160401b03811115614ee8575f5ffd5b61485485828601614d0b565b5f60208284031215614f04575f5ffd5b815160ff81168114612c67575f5ffd5b6001815b6001841115614f4f57808504811115614f3357614f33614c50565b6001841615614f4157908102905b60019390931c928002614f18565b935093915050565b5f82614f655750600161071d565b81614f7157505f61071d565b8160018114614f875760028114614f9157614fad565b600191505061071d565b60ff841115614fa257614fa2614c50565b50506001821b61071d565b5060208310610133831016604e8410600b8410161715614fd0575081810a61071d565b614fdc5f198484614f14565b805f1904821115614fef57614fef614c50565b029392505050565b5f612c6760ff841683614f57565b601f82111561185e57805f5260205f20601f840160051c8101602085101561502a5750805b601f840160051c820191505b81811015615049575f8155600101615036565b5050505050565b81516001600160401b03811115615069576150696143cb565b61507d8161507784546149b8565b84615005565b6020601f8211600181146150af575f83156150985750848201515b5f19600385901b1c1916600184901b178455615049565b5f84815260208120601f198516915b828110156150de57878501518255602094850194600190920191016150be565b50848210156150fb57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b5f6020828403121561511a575f5ffd5b81516001600160401b0381111561512f575f5ffd5b8201601f8101841361513f575f5ffd5b805161514d61449882614459565b8082825260208201915060208360051b85010192508683111561516e575f5ffd5b602084015b838110156147885780516001600160401b03811115615190575f5ffd5b61519f89602083890101614a43565b84525060209283019201615173565b5f604082016040835280845180835260608501915060608160051b8601019250602086015f5b8281101561520557605f198786030184526151f08583516140fd565b945060209384019391909101906001016151d4565b5050505082810360208401526002815261016160f51b60208201526040810191505092915050565b64022b0b937160dd1b81525f6152466005830186614ac1565b7f20616e6420737570706c7920415052206279206c656e64696e672000000000008152615276601b820186614ac1565b90507f20746f2053696c6f205632202b20676574204d65726b6c2072657761726473008152613dfe601f820185614ac1565b5f82601f8301126152b7575f5ffd5b81516152c561449882614459565b8082825260208201915060208360051b8601019250858311156152e6575f5ffd5b602085015b838110156144e45780516152fe81614549565b8352602092830192016152eb565b5f60e0828403121561531c575f5ffd5b6153246143df565b825181529050615336602083016149f0565b602082015260408201516001600160401b03811115615353575f5ffd5b61535f84828501614a43565b60408301525060608201516001600160401b0381111561537d575f5ffd5b61538984828501614e37565b60608301525060808201516001600160401b038111156153a7575f5ffd5b6153b384828501614e37565b60808301525060a08201516001600160401b038111156153d1575f5ffd5b6153dd84828501614d0b565b60a08301525060c08201516001600160401b038111156153fb575f5ffd5b615407848285016152a8565b60c08301525092915050565b5f60208284031215615423575f5ffd5b81516001600160401b03811115615438575f5ffd5b8201601f81018413615448575f5ffd5b805161545661449882614459565b8082825260208201915060208360051b850101925086831115615477575f5ffd5b602084015b838110156147885780516001600160401b03811115615499575f5ffd5b6154a88960208389010161530c565b8452506020928301920161547c565b604081525f6154c960408301856140fd565b828103602084015261466881856140fd565b5f600182016154ec576154ec614c50565b5060010190565b5f60208284031215615503575f5ffd5b81516001600160401b03811115615518575f5ffd5b6118788482850161530c565b848152608060208201525f5f855461553b816149b8565b806080860152600182165f81146155595760018114615575576155a6565b60ff19831660a087015260a082151560051b87010193506155a6565b885f5260205f205f5b8381101561559d57815488820160a0015260019091019060200161557e565b870160a0019450505b5050506001600160a01b03949094166040830152506060015292915050565b5f602082840312156155d5575f5ffd5b81516001600160401b038111156155ea575f5ffd5b8201601f810184136155fa575f5ffd5b805161560861449882614459565b80828252602082019150602060608402850101925086831115615629575f5ffd5b6020840193505b82841015613dfe5760608488031215615647575f5ffd5b61564f614407565b8451815260208086015190820152604085015161566b8161414e565b6040820152825260609390930192602090910190615630565b5f8161569257615692614c50565b505f190190565b600281106156b557634e487b7160e01b5f52602160045260245ffd5b9052565b8481526001600160a01b03848116602083015283166040820152608081016146686060830184615699565b8381526001600160a01b0383166020820152606081016118786040830184615699565b6001600160a01b0386811682528516602082015260a0604082018190525f90615732908301866142d7565b8281036060840152615744818661431a565b915050826080830152969550505050505056fee61f0a7b2953b9e28e48cc07562ad7979478dcaee972e68dcf3b10da2cba6000a26469706673582212201bcd9ad123e40d4e85179626a1b655fd578d78e135c22036e827fc2a6d3c5a4964736f6c634300081c0033
Deployed Bytecode
0x608060405234801561000f575f5ffd5b506004361061034d575f3560e01c806371a97305116101c9578063b6c8cdef116100fe578063f1faf0501161009e578063f985b0bc11610079578063f985b0bc146106d2578063fbfa77cf146106e5578063fdff667c146106ed578063ffa1ad741461059f575f5ffd5b8063f1faf050146106ad578063f55dd6c1146106b5578063f815c4ff146106ca575f5ffd5b8063c1ec4eb4116100d9578063c1ec4eb414610650578063ead0bc4714610663578063ecfa9b9114610676578063f198f5f71461069a575f5ffd5b8063b6c8cdef146105c3578063b9f5be411461062a578063bd5a74681461063d575f5ffd5b8063936725ec11610169578063a2b7722c11610144578063a2b7722c146105dc578063aa47f4e1146105ef578063aefb0751146105f7578063b600585a14610617575f5ffd5b8063936725ec1461059f5780639736374e146105c357806399f428cf146105c9575f5ffd5b806380e7ac7c116101a457806380e7ac7c1461058157806383ecf6531461058857806389816e30146105905780638c3aefa714610598575f5ffd5b806371a97305146105645780637284e4161461057957806374bac42914610581575f5ffd5b806341affeb81161029f57806350f4e4191161023f57806367cf905a1161021a57806367cf905a1461052b57806367fde573146105335780636d9894391461053b5780636f307dc31461055c575f5ffd5b806350f4e419146104df57806359498ab7146104ff5780635b0f088a14610507575f5ffd5b806348d7d9eb1161027a57806348d7d9eb146104aa5780634bde38c8146104bc5780634d8f1277146104c45780634fa5d854146104d7575f5ffd5b806341affeb8146104645780634593144c146104775780634875c9681461047f575f5ffd5b806320208ad81161030a5780632d433b28116102e55780632d433b28146104295780632ddbd13a1461044c578063394f52321461045457806341760fe61461045c575f5ffd5b806320208ad8146103cf578063278de000146103e45780632a8ba293146103f8575f5ffd5b806301ffc9a7146103515780630c56ae3b1461037957806313e63180146103935780631639ba98146103a9578063190024e0146103b15780631ec71e05146103b9575b5f5ffd5b61036461035f3660046140d6565b6106f5565b60405190151581526020015b60405180910390f35b5f5b6040516001600160a01b039091168152602001610370565b61039b610723565b604051908152602001610370565b61039b610735565b61039b610747565b6103c16107e8565b60405161037092919061412b565b6103e26103dd3660046141a2565b610b07565b005b5f5160206157585f395f51905f525461039b565b61041c604051806040016040528060058152602001640c4b8ccb8d60da1b81525081565b6040516103709190614250565b61043c610437366004614262565b610e67565b604051610370949392919061434a565b61039b610eb0565b6103e2610ec2565b61039b610f55565b6103e2610472366004614557565b610f67565b61039b611367565b60408051808201909152600f81526e53696c6f204d65726b6c204661726d60881b602082015261041c565b6060805b604051610370929190614644565b61037b61139a565b6103e26104d23660046146e4565b6113c9565b6103e261142e565b6104f26104ed366004614793565b611863565b60405161037091906147e9565b6104ae611880565b61041c604051806040016040528060058152602001640322e362e360dc1b81525081565b6104f2611912565b6103e261195e565b61054e6105493660046147fb565b611988565b60405161037092919061485e565b61037b611a8d565b61056c611aa8565b604051610370919061487f565b61041c611b11565b6001610364565b6104f2611b2d565b61039b611b38565b60606104f2565b61041c60405180604001604052806005815260200164312e302e3160d81b81525081565b5f610364565b6103e26105d7366004614891565b611d74565b61039b6105ea3660046148bf565b611d8a565b61056c611dc4565b6040805180820190915260048152634175746f60e01b602082015261041c565b61054e6106253660046147fb565b611e31565b6104f26106383660046148f0565b611f1e565b6103e261064b3660046148f0565b611f31565b6103e261065e366004614907565b611f4c565b6104f26106713660046148f0565b611f9d565b61041c604051806040016040528060058152602001640312e312e360dc1b81525081565b6103e26106a8366004614938565b612062565b61039b6120ca565b6106bd6120dc565b6040516103709190614964565b61039b6121b9565b6104f26106e0366004614976565b6121cb565b61037b612274565b6106bd61228c565b5f6106ff826122fe565b8061070e575061070e8261231e565b8061071d575061071d826122fe565b92915050565b5f61072c612342565b60020154905090565b5f61073e612342565b60090154905090565b6040805161d39560e81b60208201525f6023820181905282516006818403018152602683019384905263bfe370d960e01b9093529173cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979163bfe370d9916107a491602a01614250565b602060405180830381865af41580156107bf573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107e391906149a1565b905090565b60605f5f6107f4612342565b600c018054610802906149b8565b80601f016020809104026020016040519081016040528092919081815260200182805461082e906149b8565b80156108795780601f1061085057610100808354040283529160200191610879565b820191905f5260205f20905b81548152906001019060200180831161085c57829003601f168201915b5050505050905080515f146108915792600192509050565b5f61089a612366565b90505f6108a68261238d565b90505f816001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108e5573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061090991906149fb565b90505f5f826001600160a01b031663aecc90cb6040518163ffffffff1660e01b81526004016040805180830381865afa158015610948573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061096c9190614a16565b915091505f826001600160a01b0316856001600160a01b0316146109905782610992565b815b9050806001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109d0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109f491906149fb565b6001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015610a2e573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610a559190810190614a90565b73cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee69763be59b507610a776123b3565b6040518263ffffffff1660e01b8152600401610a9591815260200190565b5f60405180830381865af4158015610aaf573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610ad69190810190614a90565b604051602001610ae7929190614ad8565b604051602081830303815290604052600198509850505050505050509091565b610b0f612486565b5f610b1861139a565b6001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b53573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b7791906149fb565b9050855f816001600160401b03811115610b9357610b936143cb565b604051908082528060200260200182016040528015610bbc578160200160208202803683370190505b5090505f826001600160401b03811115610bd857610bd86143cb565b604051908082528060200260200182016040528015610c01578160200160208202803683370190505b5090505f5b83811015610cee578a8a82818110610c2057610c20614af8565b9050602002016020810190610c359190614262565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015610c79573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c9d91906149a1565b828281518110610caf57610caf614af8565b60200260200101818152505030838281518110610cce57610cce614af8565b6001600160a01b0390921660209283029190910190910152600101610c06565b506040516301c7ba5760e61b81526001600160a01b038c16906371ee95c090610d279085908e908e908e908e908e908e90600401614b3c565b5f604051808303815f87803b158015610d3e575f5ffd5b505af1158015610d50573d5f5f3e3d5ffd5b505050505f5b83811015610e59575f828281518110610d7157610d71614af8565b60200260200101518c8c84818110610d8b57610d8b614af8565b9050602002016020810190610da09190614262565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015610de4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0891906149a1565b610e129190614c64565b9050610e5086828e8e86818110610e2b57610e2b614af8565b9050602002016020810190610e409190614262565b6001600160a01b03169190612515565b50600101610d56565b505050505050505050505050565b606080606080610ea1856040518060400160405280600f81526020016e53696c6f204d65726b6c204661726d60881b8152506125746127db565b93509350935093509193509193565b5f610eb9612342565b60010154905090565b610eca612486565b7313d579335a6bf08ff312087486ee63bae79d249663fede401f5f5160206157585f395f51905f52610efa61139a565b6040516001600160e01b031960e085901b16815260048101929092526001600160a01b031660248201526044015f6040518083038186803b158015610f3d575f5ffd5b505af4158015610f4f573d5f5f3e3d5ffd5b50505050565b5f610f5e612342565b600a0154905090565b5f610f70612b69565b805490915060ff600160401b82041615906001600160401b03165f81158015610f965750825b90505f826001600160401b03166001148015610fb15750303b155b905081158015610fbf575080155b15610fdd5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561100757845460ff60401b1916600160401b1785555b8751600214158061101a57508651600114155b806110255750855115155b15611043576040516363cf6b6160e01b815260040160405180910390fd5b5f611080895f8151811061105957611059614af8565b6020026020010151895f8151811061107357611073614af8565b6020026020010151612b91565b9050806080015151600314158061109d57508060a0015151600114155b806110ac575060c08101515115155b156110ca576040516325b769d160e11b815260040160405180910390fd5b6040805160018082528183019092525f91602080830190803683370190505090505f6110f58361238d565b9050806001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611133573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061115791906149fb565b825f8151811061116957611169614af8565b60200260200101906001600160a01b031690816001600160a01b0316815250506111f18b5f8151811061119e5761119e614af8565b60200260200101516040518060400160405280600f81526020016e53696c6f204d65726b6c204661726d60881b8152508d6001815181106111e1576111e1614af8565b6020026020010151855f5f612c6e565b61122d8b5f8151811061120657611206614af8565b60200260200101518b5f8151811061122057611220614af8565b6020026020010151612d12565b611265815f19845f8151811061124557611245614af8565b60200260200101516001600160a01b0316612d969092919063ffffffff16565b8260a001515f8151811061127b5761127b614af8565b60200260200101516001146112e35760405162461bcd60e51b815260206004820152602360248201527f4f6e6c7920436f6c6c61746572616c20737570706f727465642c2073656520236044820152620cce4d60ea1b60648201526084015b60405180910390fd5b5f6112ed84612e25565b90506001600160a01b03811615611313576113136001600160a01b038316825f19612d96565b50505050831561135d57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050565b5f6107e361139660017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f1614c64565b5490565b5f6107e361139660017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d6614c64565b6113d1612486565b5f6113da612342565b82519091506113f290600b8301906020850190613f78565b507fd319c6758f17094777edee94fbe0651a574464c07a5167e481d19cc2e0acf133826040516114229190614964565b60405180910390a15050565b611436612e3d565b61143e612e6e565b5f611447612342565b805460408051637299470360e11b815281519394506001600160a01b03909216925f92849263e5328e06926004808401938290030181865afa15801561148f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b39190614c86565b509050801561185e575f6114c561139a565b60088501549091505f8080806114d9612eeb565b93509350935093505f6114e95f90565b6115d45761151185878151811061150257611502614af8565b60200260200101518484613455565b84878151811061152357611523614af8565b602002602001018181516115379190614cb0565b9052506040516308dc79a160e01b81525f907313d579335a6bf08ff312087486ee63bae79d2496906308dc79a190611579908b908e908b908b90600401614cc3565b5f60405180830381865af4158015611593573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526115ba9190810190614d66565b60018c81015493509091506115cd613461565b50506117e9565b604051633596603f60e01b81527313d579335a6bf08ff312087486ee63bae79d249690633596603f9061160b9087906004016147e9565b602060405180830381865af4158015611626573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061164a9190614d97565b156116af576040516336ac731760e11b81526001600160a01b038a1690636d58e62e9061167d9088908890600401614644565b5f604051808303815f87803b158015611694575f5ffd5b505af11580156116a6573d5f5f3e3d5ffd5b505050506117cb565b5f6116b8611880565b9150505f86516001600160401b038111156116d5576116d56143cb565b6040519080825280602002602001820160405280156116fe578160200160208202803683370190505b50905060076301e133808d60020154426117189190614c64565b845f8151811061172a5761172a614af8565b602002602001015161173c9190614db0565b6117469190614dc7565b6117509190614dc7565b815f8151811061176257611762614af8565b60209081029190910101526040516336ac731760e11b81526001600160a01b038c1690636d58e62e9061179b908a908590600401614644565b5f604051808303815f87803b1580156117b2575f5ffd5b505af11580156117c4573d5f5f3e3d5ffd5b5050505050505b6117e0855f8151811061150257611502614af8565b506117e9613461565b60405163640f244560e01b81527313d579335a6bf08ff312087486ee63bae79d24969063640f24459061182a908d908b908a908a908f908990600401614de6565b5f6040518083038186803b158015611840575f5ffd5b505af4158015611852573d5f5f3e3d5ffd5b50505050505050505050505b505050565b606061186d612e3d565b6118788484846136b5565b949350505050565b60608061188b6137cf565b604051633f8b51a560e21b815291935091507313d579335a6bf08ff312087486ee63bae79d24969063fe2d4694906118c99085908590600401614644565b5f60405180830381865af41580156118e3573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261190a9190810190614e9b565b915091509091565b60408051600180825281830190925260609160208083019080368337019050509050670de0b6b3a7640000815f8151811061194f5761194f614af8565b60200260200101818152505090565b611966613893565b611977611971610eb0565b306139ad565b506001611982612342565b600a0155565b60605f835160011480156119d4575061199f612342565b6006015484516001600160a01b039091169085905f906119c1576119c1614af8565b60200260200101516001600160a01b0316145b8015611a0b57505f6001600160a01b0316845f815181106119f7576119f7614af8565b60200260200101516001600160a01b031614155b15611a77578251600114611a3257604051630ef9926760e21b815260040160405180910390fd5b825f81518110611a4457611a44614af8565b60200260200101519050611a70835f81518110611a6357611a63614af8565b6020026020010151613a1f565b9150611a86565b611a818484613a27565b915091505b9250929050565b5f611a96612342565b600601546001600160a01b0316919050565b6060611ab2612342565b600501805480602002602001604051908101604052809291908181526020018280548015611b0757602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311611ae9575b5050505050905090565b60605f611b1c612366565b9050611b2781612574565b91505090565b60606107e35f611f9d565b5f5f611b42612366565b90505f611b4e8261238d565b90505f816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b8d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bb191906149fb565b90505f611bbc61139a565b6001600160a01b03166349b5fdb46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bf7573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c1b91906149fb565b6040516341976e0960e01b81526001600160a01b0384811660048301529192505f918316906341976e09906024016040805180830381865afa158015611c63573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c879190614c86565b509050826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cc6573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611cea9190614ef4565b611cf590600a614ff7565b81856001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d32573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d5691906149a1565b611d609190614db0565b611d6a9190614dc7565b9550505050505090565b611d7c612e3d565b611d868282613a34565b5050565b5f611d93612e3d565b5f611d9c612342565b905080600201545f03611db0574260028201555b611dbb836001613abc565b9150505b919050565b60605f5160206157585f395f51905f52600101805480602002602001604051908101604052809291908181526020018280548015611b0757602002820191905f5260205f209081546001600160a01b03168152600190910190602001808311611ae9575050505050905090565b60605f83516001148015611e7d5750611e48612342565b6006015484516001600160a01b039091169085905f90611e6a57611e6a614af8565b60200260200101516001600160a01b0316145b8015611eb457505f6001600160a01b0316845f81518110611ea057611ea0614af8565b60200260200101516001600160a01b031614155b15611f14578251600114611edb57604051630ef9926760e21b815260040160405180910390fd5b825f81518110611eed57611eed614af8565b60200260200101519050611a70835f81518110611f0c57611f0c614af8565b506060919050565b611a818484613b96565b6060611f28612e3d565b61071d82613ba2565b611f39612486565b5f611f42612342565b6009019190915550565b611f54612486565b5f611f5d612342565b9050600c8101611f6d8382615050565b507fd65900dd44764cfc9d7d6f6a36f82c15f38955a604922fa324ed9516e26e186f826040516114229190614250565b60605f611fa8612366565b90505f611fb48261238d565b604080516001808252818301909252919250602080830190803683370190505060405163ce96cb7760e01b81523060048201529093506001600160a01b0382169063ce96cb7790602401602060405180830381865afa158015612019573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061203d91906149a1565b835f8151811061204f5761204f614af8565b6020026020010181815250505050919050565b61206a612486565b60405163bdac7ca360e01b81523060048201526001600160a01b03828116602483015283169063bdac7ca3906044015f604051808303815f87803b1580156120b0575f5ffd5b505af11580156120c2573d5f5f3e3d5ffd5b505050505050565b5f6120d3612342565b60040154905090565b60606120e6612342565b600b01805480602002602001604051908101604052809291908181526020015f905b828210156121b0578382905f5260205f20018054612125906149b8565b80601f0160208091040260200160405190810160405280929190818152602001828054612151906149b8565b801561219c5780601f106121735761010080835404028352916020019161219c565b820191905f5260205f20905b81548152906001019060200180831161217f57829003601f168201915b505050505081526020019060010190612108565b50505050905090565b5f6121c2612342565b60030154905090565b60606121d5612e3d565b7313d579335a6bf08ff312087486ee63bae79d24966325567aef6121f7612342565b6040516001600160e01b031960e084901b168152600481019190915260248101879052604481018690526001600160a01b03851660648201526084015f60405180830381865af415801561224d573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526118789190810190614d66565b5f61227d612342565b546001600160a01b0316919050565b604080516001808252818301909252606091816020015b60608152602001906001900390816122a35790505090506040518060400160405280600b81526020016a436f6d706f756e64696e6760a81b815250815f815181106122f0576122f0614af8565b602002602001018190525090565b5f6001600160e01b031982166396cf43c560e01b148061071d575061071d825b5f6001600160e01b0319821663d1b87f2f60e01b148061071d575061071d82613bad565b7fb14b643f49bed6a2c6693bbd50f68dc950245db265c66acadbfa51ccc8c3ba0090565b61236e613fcc565b6107e361237961139a565b5f5160206157585f395f51905f5254612b91565b5f81608001515f815181106123a4576123a4614af8565b60200260200101519050919050565b5f5f6123bd612366565b90506123c88161238d565b6001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa158015612403573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061242791906149fb565b6001600160a01b031663189e17e46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612462573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b2791906149a1565b61248e61139a565b6040516336b87bd760e11b81523360048201526001600160a01b039190911690636d70f7ae90602401602060405180830381865afa1580156124d2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124f69190614d97565b61251357604051631f0853c160e21b815260040160405180910390fd5b565b6040516001600160a01b0383811660248301526044820183905261185e91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050613bd1565b606073cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697631dfab92873cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee69763fbcadbe985606001516040518263ffffffff1660e01b81526004016125cb919061487f565b5f60405180830381865af41580156125e5573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261260c919081019061510a565b6040518263ffffffff1660e01b815260040161262891906151ae565b5f60405180830381865af4158015612642573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526126699190810190614a90565b6126728361238d565b6001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156126ad573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126d191906149fb565b6001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa15801561270b573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526127329190810190614a90565b73cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee69763be59b5076127546123b3565b6040518263ffffffff1660e01b815260040161277291815260200190565b5f60405180830381865af415801561278c573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526127b39190810190614a90565b6040516020016127c59392919061522d565b6040516020818303038152906040529050919050565b60608080805f60405190808252806020026020018201604052801561280a578160200160208202803683370190505b50604080515f808252602082019092529194505090505f876001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa15801561285d573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061288191906149fb565b6001600160a01b031663871fd6826040518163ffffffff1660e01b81526004015f60405180830381865afa1580156128bb573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526128e29190810190615413565b80519091505f805b828110156129b2575f84828151811061290557612905614af8565b60200260200101519050805f01515f148015612998575060408082015190516310d24b2160e11b815273cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697916321a496429161295991908f906004016154b7565b602060405180830381865af4158015612974573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129989190614d97565b156129a9576129a6836154db565b92505b506001016128ea565b50806001600160401b038111156129cb576129cb6143cb565b6040519080825280602002602001820160405280156129fe57816020015b60608152602001906001900390816129e95790505b509650806001600160401b03811115612a1957612a196143cb565b604051908082528060200260200182016040528015612a42578160200160208202803683370190505b5094505f90505f5b82811015612b5c575f848281518110612a6557612a65614af8565b60200260200101519050805f01515f148015612af8575060408082015190516310d24b2160e11b815273cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697916321a4964291612ab991908f906004016154b7565b602060405180830381865af4158015612ad4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612af89190614d97565b15612b535781878481518110612b1057612b10614af8565b602002602001018181525050612b29818b63ffffffff16565b898481518110612b3b57612b3b614af8565b602002602001018190525082612b50906154db565b92505b50600101612a4a565b5050505093509350935093565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0061071d565b612b99613fcc565b826001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015612bd5573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bf991906149fb565b6001600160a01b031663538a85a1836040518263ffffffff1660e01b8152600401612c2691815260200190565b5f60405180830381865afa158015612c40573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612c6791908101906154f3565b9392505050565b612c76613c3d565b612c7f86613c62565b5f612c88612342565b600881018390556006810180546001600160a01b0319166001600160a01b03861617905584519091508690869086908690869060078701905f9088908290612cd990600584019060208a0190614010565b5081546001600160a01b03808a166101009390930a9283029202191617905550612d038682615050565b50505050505050505050505050565b612d1a613c3d565b7313d579335a6bf08ff312087486ee63bae79d2496634ab3b02f5f5160206157585f395f51905f52612d4a612342565b60070185856040518563ffffffff1660e01b8152600401612d6e9493929190615524565b5f6040518083038186803b158015612d84575f5ffd5b505af41580156120c2573d5f5f3e3d5ffd5b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052612de78482613dbf565b610f4f576040516001600160a01b0384811660248301525f6044830152612e1b91869182169063095ea7b390606401612542565b610f4f8482613bd1565b5f81608001516002815181106123a4576123a4614af8565b612e45612342565b546001600160a01b03163314612513576040516362df054560e01b815260040160405180910390fd5b306001600160a01b03166374bac4296040518163ffffffff1660e01b8152600401602060405180830381865afa158015612eaa573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ece9190614d97565b612513576040516309ea311f60e11b815260040160405180910390fd5b6060806060805f612efa612342565b90505f5160206157585f395f51905f52612f12611aa8565b955085516001600160401b03811115612f2d57612f2d6143cb565b604051908082528060200260200182016040528015612f56578160200160208202803683370190505b5060018201805460408051602080840282018101909252828152939850830182828015612faa57602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311612f8c575b5050835193975083925050506001600160401b03811115612fcd57612fcd6143cb565b604051908082528060200260200182016040528015612ff6578160200160208202803683370190505b5093505f613002612366565b90505f61300e8261238d565b60018601546040516370a0823160e01b8152306004820152919250906001600160a01b038316906307a2d13a9082906370a0823190602401602060405180830381865afa158015613061573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061308591906149a1565b6040518263ffffffff1660e01b81526004016130a391815260200190565b602060405180830381865afa1580156130be573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130e291906149a1565b6130ec9190614c64565b885f815181106130fe576130fe614af8565b6020026020010181815250505f61311483612e25565b90506001600160a01b0381161561319057604051633bd73ee360e21b81523060048201526001600160a01b0382169063ef5cfb8c906024015f604051808303815f875af1158015613167573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261318e91908101906155c5565b505b5f61319a84613e08565b90505f6001600160a01b0382166131b1575f613211565b816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156131ed573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061321191906149fb565b90505f5b86811015613446577313d579335a6bf08ff312087486ee63bae79d249663e3d670d78c838151811061324957613249614af8565b60200260200101516040518263ffffffff1660e01b815260040161327c91906001600160a01b0391909116815260200190565b602060405180830381865af4158015613297573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132bb91906149a1565b8a82815181106132cd576132cd614af8565b602002602001018181525050816001600160a01b03168b82815181106132f5576132f5614af8565b60200260200101516001600160a01b031614801561331b57506001600160a01b03831615155b1561343e5760405163e3d670d760e01b81526001600160a01b03841660048201525f907313d579335a6bf08ff312087486ee63bae79d24969063e3d670d790602401602060405180830381865af4158015613378573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061339c91906149a1565b9050801561343c576040516314e726f160e31b8152600481018290525f60248201526001600160a01b0385169063a7393788906044016020604051808303815f875af11580156133ee573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061341291906149a1565b8b838151811061342457613424614af8565b602002602001018181516134389190614cb0565b9052505b505b600101613215565b50505050505050505090919293565b5f611878848484613e20565b5f61346a611aa8565b80519091505f816001600160401b03811115613488576134886143cb565b6040519080825280602002602001820160405280156134b1578160200160208202803683370190505b5090505f5f5b838110156135a8577313d579335a6bf08ff312087486ee63bae79d249663e3d670d78683815181106134eb576134eb614af8565b60200260200101516040518263ffffffff1660e01b815260040161351e91906001600160a01b0391909116815260200190565b602060405180830381865af4158015613539573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061355d91906149a1565b83828151811061356f5761356f614af8565b60200260200101818152505082818151811061358d5761358d614af8565b60200260200101515f146135a057600191505b6001016134b7565b505f6135b2612366565b90505f6135be8261238d565b90505f6135c9612342565b6040516370a0823160e01b81523060048201529091506001600160a01b038316906307a2d13a9082906370a0823190602401602060405180830381865afa158015613616573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061363a91906149a1565b6040518263ffffffff1660e01b815260040161365891815260200190565b602060405180830381865afa158015613673573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061369791906149a1565b600182015583156136ac5761135d855f613abc565b50505050505050565b60605f6136c0612366565b90505f6136cc8261238d565b9050846001600160a01b03851630036136ed57806136e981615684565b9150505b604051635c19be1560e11b81526001600160a01b0383169063b8337c2a90613720908490899030906001906004016156b9565b6020604051808303815f875af115801561373c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061376091906149a1565b50604080516001808252818301909252906020808301908036833701905050935085845f8151811061379457613794614af8565b6020026020010181815250505f6137a9612342565b905086816001015f8282546137be9190614c64565b909155509498975050505050505050565b6060805f6137db612342565b6005810180546040805160208084028201810190925282815293945083018282801561382e57602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311613810575b509396506001935061383f92505050565b604051908082528060200260200182016040528015613868578160200160208202803683370190505b5091508060010154825f8151811061388257613882614af8565b602002602001018181525050509091565b5f61389c61139a565b9050336001600160a01b0316816001600160a01b0316635aa6e6756040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138e4573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061390891906149fb565b6001600160a01b0316148061398d5750336001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561395e573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061398291906149fb565b6001600160a01b0316145b6139aa576040516354299b6f60e01b815260040160405180910390fd5b50565b60605f6139b8612342565b905061187881600501805480602002602001604051908101604052809291908181526020018280548015613a1357602002820191905f5260205f20905b81546001600160a01b031681526001909101906020018083116139f5575b505050505085856136b5565b60608061071d565b60605f611a818484613b96565b5f613a3d612342565b600601546001600160a01b031614613a7c576040518060400160405280600f81526020016e1b9bdd081a5b5c1b195b595b9d1959608a1b815250613aa3565b6040518060400160405280600d81526020016c6e6f20756e6465726c79696e6760981b8152505b60405162461bcd60e51b81526004016112da9190614250565b5f5f613ac6612366565b90505f613ad1612342565b90505f613add8361238d565b9050855f81518110613af157613af1614af8565b60200260200101519350835f14613b8d5760405163b7ec8d4b60e01b81526001600160a01b0382169063b7ec8d4b90613b3390879030906001906004016156e4565b6020604051808303815f875af1158015613b4f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b7391906149a1565b5083826001015f828254613b879190614cb0565b90915550505b50505092915050565b60605f611a8183613ead565b60605f613a3d612342565b5f6001600160e01b03198216637a2a253160e01b148061071d575061071d82613f2b565b5f5f60205f8451602086015f885af180613bf0576040513d5f823e3d81fd5b50505f513d91508115613c07578060011415613c14565b6001600160a01b0384163b155b15610f4f57604051635274afe760e01b81526001600160a01b03851660048201526024016112da565b613c45613f5f565b61251357604051631afcd79f60e31b815260040160405180910390fd5b613c6a613c3d565b6001600160a01b03811615801590613cf357505f6001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613cc3573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ce791906149fb565b6001600160a01b031614155b613d10576040516371c42ac360e01b815260040160405180910390fd5b613d43613d3e60017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d6614c64565b829055565b613d7543613d7260017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f1614c64565b55565b604080516001600160a01b0383168152426020820152438183015290517f1a2dd071001ebf6e03174e3df5b305795a4ad5d41d8fdb9ba41dbbe2367134269181900360600190a150565b5f5f5f5f60205f8651602088015f8a5af192503d91505f519050828015613dfe57508115613df05780600114613dfe565b5f866001600160a01b03163b115b9695505050505050565b5f81608001516001815181106123a4576123a4614af8565b5f7313d579335a6bf08ff312087486ee63bae79d249663b9f637cd613e4361139a565b868686613e4e610735565b6040518663ffffffff1660e01b8152600401613e6e959493929190615707565b602060405180830381865af4158015613e89573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061187891906149a1565b6040805160018082528183019092526060915f919060208083019080368337019050509150825f81518110613ee457613ee4614af8565b6020026020010151825f81518110613efe57613efe614af8565b602002602001018181525050815f81518110613f1c57613f1c614af8565b60200260200101519050915091565b5f6001600160e01b03198216630f1ec81f60e41b148061071d57506301ffc9a760e01b6001600160e01b031983161461071d565b5f613f68612b69565b54600160401b900460ff16919050565b828054828255905f5260205f20908101928215613fbc579160200282015b82811115613fbc5782518290613fac9082615050565b5091602001919060010190613f96565b50613fc892915061406f565b5090565b6040518060e001604052805f81526020015f6001600160a01b0316815260200160608152602001606081526020016060815260200160608152602001606081525090565b828054828255905f5260205f20908101928215614063579160200282015b8281111561406357825182546001600160a01b0319166001600160a01b0390911617825560209092019160019091019061402e565b50613fc892915061408b565b80821115613fc8575f614082828261409f565b5060010161406f565b5b80821115613fc8575f815560010161408c565b5080546140ab906149b8565b5f825580601f106140ba575050565b601f0160209004905f5260205f20908101906139aa919061408b565b5f602082840312156140e6575f5ffd5b81356001600160e01b031981168114612c67575f5ffd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b604081525f61413d60408301856140fd565b905082151560208301529392505050565b6001600160a01b03811681146139aa575f5ffd5b5f5f83601f840112614172575f5ffd5b5081356001600160401b03811115614188575f5ffd5b6020830191508360208260051b8501011115611a86575f5ffd5b5f5f5f5f5f5f5f6080888a0312156141b8575f5ffd5b87356141c38161414e565b965060208801356001600160401b038111156141dd575f5ffd5b6141e98a828b01614162565b90975095505060408801356001600160401b03811115614207575f5ffd5b6142138a828b01614162565b90955093505060608801356001600160401b03811115614231575f5ffd5b61423d8a828b01614162565b989b979a50959850939692959293505050565b602081525f612c6760208301846140fd565b5f60208284031215614272575f5ffd5b8135612c678161414e565b5f82825180855260208501945060208160051b830101602085015f5b838110156142cb57601f198584030188526142b58383516140fd565b6020988901989093509190910190600101614299565b50909695505050505050565b5f8151808452602084019350602083015f5b828110156143105781516001600160a01b03168652602095860195909101906001016142e9565b5093949350505050565b5f8151808452602084019350602083015f5b8281101561431057815186526020958601959091019060010161432c565b608081525f61435c608083018761427d565b828103602084015261436e81876142d7565b90508281036040840152614382818661431a565b8381036060850152845180825260208087019350909101905f5b818110156143bd57835160020b83526020938401939092019160010161439c565b509098975050505050505050565b634e487b7160e01b5f52604160045260245ffd5b60405160e081016001600160401b0381118282101715614401576144016143cb565b60405290565b604051606081016001600160401b0381118282101715614401576144016143cb565b604051601f8201601f191681016001600160401b0381118282101715614451576144516143cb565b604052919050565b5f6001600160401b03821115614471576144716143cb565b5060051b60200190565b5f82601f83011261448a575f5ffd5b813561449d61449882614459565b614429565b8082825260208201915060208360051b8601019250858311156144be575f5ffd5b602085015b838110156144e45780356144d68161414e565b8352602092830192016144c3565b5095945050505050565b5f82601f8301126144fd575f5ffd5b813561450b61449882614459565b8082825260208201915060208360051b86010192508583111561452c575f5ffd5b602085015b838110156144e4578035835260209283019201614531565b8060020b81146139aa575f5ffd5b5f5f5f60608486031215614569575f5ffd5b83356001600160401b0381111561457e575f5ffd5b61458a8682870161447b565b93505060208401356001600160401b038111156145a5575f5ffd5b6145b1868287016144ee565b92505060408401356001600160401b038111156145cc575f5ffd5b8401601f810186136145dc575f5ffd5b80356145ea61449882614459565b8082825260208201915060208360051b85010192508883111561460b575f5ffd5b6020840193505b8284101561463657833561462581614549565b825260209384019390910190614612565b809450505050509250925092565b604081525f61465660408301856142d7565b8281036020840152614668818561431a565b95945050505050565b5f6001600160401b03821115614689576146896143cb565b50601f01601f191660200190565b5f82601f8301126146a6575f5ffd5b81356146b461449882614671565b8181528460208386010111156146c8575f5ffd5b816020850160208301375f918101602001919091529392505050565b5f602082840312156146f4575f5ffd5b81356001600160401b03811115614709575f5ffd5b8201601f81018413614719575f5ffd5b803561472761449882614459565b8082825260208201915060208360051b850101925086831115614748575f5ffd5b602084015b838110156147885780356001600160401b0381111561476a575f5ffd5b61477989602083890101614697565b8452506020928301920161474d565b509695505050505050565b5f5f5f606084860312156147a5575f5ffd5b83356001600160401b038111156147ba575f5ffd5b6147c68682870161447b565b9350506020840135915060408401356147de8161414e565b809150509250925092565b602081525f612c67602083018461431a565b5f5f6040838503121561480c575f5ffd5b82356001600160401b03811115614821575f5ffd5b61482d8582860161447b565b92505060208301356001600160401b03811115614848575f5ffd5b614854858286016144ee565b9150509250929050565b604081525f614870604083018561431a565b90508260208301529392505050565b602081525f612c6760208301846142d7565b5f5f604083850312156148a2575f5ffd5b8235915060208301356148b48161414e565b809150509250929050565b5f602082840312156148cf575f5ffd5b81356001600160401b038111156148e4575f5ffd5b611878848285016144ee565b5f60208284031215614900575f5ffd5b5035919050565b5f60208284031215614917575f5ffd5b81356001600160401b0381111561492c575f5ffd5b61187884828501614697565b5f5f60408385031215614949575f5ffd5b82356149548161414e565b915060208301356148b48161414e565b602081525f612c67602083018461427d565b5f5f5f60608486031215614988575f5ffd5b833592506020840135915060408401356147de8161414e565b5f602082840312156149b1575f5ffd5b5051919050565b600181811c908216806149cc57607f821691505b6020821081036149ea57634e487b7160e01b5f52602260045260245ffd5b50919050565b8051611dbf8161414e565b5f60208284031215614a0b575f5ffd5b8151612c678161414e565b5f5f60408385031215614a27575f5ffd5b8251614a328161414e565b60208401519092506148b48161414e565b5f82601f830112614a52575f5ffd5b8151614a6061449882614671565b818152846020838601011115614a74575f5ffd5b8160208501602083015e5f918101602001919091529392505050565b5f60208284031215614aa0575f5ffd5b81516001600160401b03811115614ab5575f5ffd5b61187884828501614a43565b5f81518060208401855e5f93019283525090919050565b5f614ae38285614ac1565b61016160f51b81526146686002820185614ac1565b634e487b7160e01b5f52603260045260245ffd5b8183525f6001600160fb1b03831115614b23575f5ffd5b8260051b80836020870137939093016020019392505050565b608081525f614b4e608083018a6142d7565b8281036020808501919091528882528991015f5b89811015614b92578235614b758161414e565b6001600160a01b0316825260209283019290910190600101614b62565b508381036040850152614ba681888a614b0c565b8481036060860152858152915050602080820190600586901b830101865f36829003601e19015b88821015614c3d57858403601f190185528235818112614beb575f5ffd5b8a016020810190356001600160401b03811115614c06575f5ffd5b8060051b3603821315614c17575f5ffd5b614c22868284614b0c565b95505050602083019250602085019450600182019150614bcd565b50919d9c50505050505050505050505050565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561071d5761071d614c50565b80518015158114611dbf575f5ffd5b5f5f60408385031215614c97575f5ffd5b82519150614ca760208401614c77565b90509250929050565b8082018082111561071d5761071d614c50565b6001600160a01b038581168252841660208201526080604082018190525f90614cee908301856142d7565b8281036060840152614d00818561431a565b979650505050505050565b5f82601f830112614d1a575f5ffd5b8151614d2861449882614459565b8082825260208201915060208360051b860101925085831115614d49575f5ffd5b602085015b838110156144e4578051835260209283019201614d4e565b5f60208284031215614d76575f5ffd5b81516001600160401b03811115614d8b575f5ffd5b61187884828501614d0b565b5f60208284031215614da7575f5ffd5b612c6782614c77565b808202811582820484141761071d5761071d614c50565b5f82614de157634e487b7160e01b5f52601260045260245ffd5b500490565b8681526001600160a01b038616602082015260c0604082018190525f90614e0f908301876142d7565b8281036060840152614e21818761431a565b6080840195909552505060a00152949350505050565b5f82601f830112614e46575f5ffd5b8151614e5461449882614459565b8082825260208201915060208360051b860101925085831115614e75575f5ffd5b602085015b838110156144e4578051614e8d8161414e565b835260209283019201614e7a565b5f5f60408385031215614eac575f5ffd5b82516001600160401b03811115614ec1575f5ffd5b614ecd85828601614e37565b92505060208301516001600160401b03811115614ee8575f5ffd5b61485485828601614d0b565b5f60208284031215614f04575f5ffd5b815160ff81168114612c67575f5ffd5b6001815b6001841115614f4f57808504811115614f3357614f33614c50565b6001841615614f4157908102905b60019390931c928002614f18565b935093915050565b5f82614f655750600161071d565b81614f7157505f61071d565b8160018114614f875760028114614f9157614fad565b600191505061071d565b60ff841115614fa257614fa2614c50565b50506001821b61071d565b5060208310610133831016604e8410600b8410161715614fd0575081810a61071d565b614fdc5f198484614f14565b805f1904821115614fef57614fef614c50565b029392505050565b5f612c6760ff841683614f57565b601f82111561185e57805f5260205f20601f840160051c8101602085101561502a5750805b601f840160051c820191505b81811015615049575f8155600101615036565b5050505050565b81516001600160401b03811115615069576150696143cb565b61507d8161507784546149b8565b84615005565b6020601f8211600181146150af575f83156150985750848201515b5f19600385901b1c1916600184901b178455615049565b5f84815260208120601f198516915b828110156150de57878501518255602094850194600190920191016150be565b50848210156150fb57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b5f6020828403121561511a575f5ffd5b81516001600160401b0381111561512f575f5ffd5b8201601f8101841361513f575f5ffd5b805161514d61449882614459565b8082825260208201915060208360051b85010192508683111561516e575f5ffd5b602084015b838110156147885780516001600160401b03811115615190575f5ffd5b61519f89602083890101614a43565b84525060209283019201615173565b5f604082016040835280845180835260608501915060608160051b8601019250602086015f5b8281101561520557605f198786030184526151f08583516140fd565b945060209384019391909101906001016151d4565b5050505082810360208401526002815261016160f51b60208201526040810191505092915050565b64022b0b937160dd1b81525f6152466005830186614ac1565b7f20616e6420737570706c7920415052206279206c656e64696e672000000000008152615276601b820186614ac1565b90507f20746f2053696c6f205632202b20676574204d65726b6c2072657761726473008152613dfe601f820185614ac1565b5f82601f8301126152b7575f5ffd5b81516152c561449882614459565b8082825260208201915060208360051b8601019250858311156152e6575f5ffd5b602085015b838110156144e45780516152fe81614549565b8352602092830192016152eb565b5f60e0828403121561531c575f5ffd5b6153246143df565b825181529050615336602083016149f0565b602082015260408201516001600160401b03811115615353575f5ffd5b61535f84828501614a43565b60408301525060608201516001600160401b0381111561537d575f5ffd5b61538984828501614e37565b60608301525060808201516001600160401b038111156153a7575f5ffd5b6153b384828501614e37565b60808301525060a08201516001600160401b038111156153d1575f5ffd5b6153dd84828501614d0b565b60a08301525060c08201516001600160401b038111156153fb575f5ffd5b615407848285016152a8565b60c08301525092915050565b5f60208284031215615423575f5ffd5b81516001600160401b03811115615438575f5ffd5b8201601f81018413615448575f5ffd5b805161545661449882614459565b8082825260208201915060208360051b850101925086831115615477575f5ffd5b602084015b838110156147885780516001600160401b03811115615499575f5ffd5b6154a88960208389010161530c565b8452506020928301920161547c565b604081525f6154c960408301856140fd565b828103602084015261466881856140fd565b5f600182016154ec576154ec614c50565b5060010190565b5f60208284031215615503575f5ffd5b81516001600160401b03811115615518575f5ffd5b6118788482850161530c565b848152608060208201525f5f855461553b816149b8565b806080860152600182165f81146155595760018114615575576155a6565b60ff19831660a087015260a082151560051b87010193506155a6565b885f5260205f205f5b8381101561559d57815488820160a0015260019091019060200161557e565b870160a0019450505b5050506001600160a01b03949094166040830152506060015292915050565b5f602082840312156155d5575f5ffd5b81516001600160401b038111156155ea575f5ffd5b8201601f810184136155fa575f5ffd5b805161560861449882614459565b80828252602082019150602060608402850101925086831115615629575f5ffd5b6020840193505b82841015613dfe5760608488031215615647575f5ffd5b61564f614407565b8451815260208086015190820152604085015161566b8161414e565b6040820152825260609390930192602090910190615630565b5f8161569257615692614c50565b505f190190565b600281106156b557634e487b7160e01b5f52602160045260245ffd5b9052565b8481526001600160a01b03848116602083015283166040820152608081016146686060830184615699565b8381526001600160a01b0383166020820152606081016118786040830184615699565b6001600160a01b0386811682528516602082015260a0604082018190525f90615732908301866142d7565b8281036060840152615744818661431a565b915050826080830152969550505050505056fee61f0a7b2953b9e28e48cc07562ad7979478dcaee972e68dcf3b10da2cba6000a26469706673582212201bcd9ad123e40d4e85179626a1b655fd578d78e135c22036e827fc2a6d3c5a4964736f6c634300081c0033
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in S
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
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.