Source Code
Overview
ETH Balance
0 ETH
ETH 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 Source Code Verified (Exact Match)
Contract Name:
LiquidStabilityPool
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 1 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {ERC4626Upgradeable, ERC20Upgradeable, IERC20, Math, SafeERC20} from "@openzeppelin-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {UUPSUpgradeable} from "@openzeppelin-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {PriceLib} from "src/libraries/PriceLib.sol";
import {TokenValidationLib} from "src/libraries/TokenValidationLib.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";
import {FeeLib} from "src/libraries/FeeLib.sol";
import {PropMath} from "src/dependencies/PropMath.sol";
import {ILiquidStabilityPool} from "src/interfaces/core/ILiquidStabilityPool.sol";
import {IPriceFeed} from "src/interfaces/core/IPriceFeed.sol";
import {IDebtToken} from "src/interfaces/core/IDebtToken.sol";
import {ICore} from "src/interfaces/core/ICore.sol";
import {IRebalancer} from "src/interfaces/utils/integrations/IRebalancer.sol";
import {IAsset} from "src/interfaces/utils/tokens/IAsset.sol";
/**
@title Stability Pool
@notice Based on Liquity's `StabilityPool`
https://github.com/liquity/dev/blob/main/packages/contracts/contracts/StabilityPool.sol
Implementation modified to support multiple collaterals. Deposits into
the liquid stability pool may be used to liquidate any supported collateral type.
*/
contract LiquidStabilityPool is ERC4626Upgradeable, UUPSUpgradeable {
using Math for uint;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using PriceLib for uint;
using TokenValidationLib for address;
using TokenValidationLib for address[];
using EmissionsLib for EmissionsLib.BalanceData;
using EmissionsLib for EmissionsLib.EmissionSchedule;
using SafeCast for uint;
using FeeLib for uint;
uint128 public constant SUNSET_DURATION = 7 days;
uint constant WAD = 1e18;
uint constant BP = 1e4;
// keccak256(abi.encode(uint(keccak256("openzeppelin.storage.LiquidStabilityPool")) - 1)) & ~bytes32(uint(0xff))
bytes32 private constant LiquidStabilityPoolStorageLocation = 0x3c2bbd5b01c023780ac7877400fd851b17fd98c152afdb1efc02015acd68a300;
function _getLSPStorage() internal pure returns (ILiquidStabilityPool.LSPStorage storage store) {
assembly {
store.slot := LiquidStabilityPoolStorageLocation
}
}
event CollateralOverwritten(address oldCollateral, address newCollateral);
event AssetsWithdraw(
address indexed receiver,
uint shares,
address[] tokens,
uint[] amounts
);
event ExtraAssetAdded(address token);
event ExtraAssetRemoved(address token);
event ProtocolRegistered(
address indexed factory,
address indexed liquidationManager
);
event ProtocolBlacklisted(address indexed factoryRemoved, address indexed LMremoved);
event Offset(address collateral, uint debtToOffset, uint collToAdd, uint collSurplusAmount);
event Rebalance(address indexed sentCurrency, address indexed receivedCurrency, uint sentAmount, uint receivedAmount, uint sentValue, uint receivedValue);
error AddressZero();
error NoPriceFeed();
error OnlyOwner();
error TokenCannotBeDebtToken();
error TokenCannotBeExtraAsset();
error CallerNotFactory();
error CollateralIsSunsetting();
error ExistingCollateral();
error CollateralMustBeSunset();
error BalanceRemaining();
error Paused();
error BootstrapPeriod();
error InvalidArrayLength();
error LastTokenMustBeDebtToken();
error CallerNotLM();
error SameTokens();
error BelowThreshold();
error ZeroTotalSupply();
error TokenMustBeExtraAsset();
error TokenIsVesting();
error InvalidThreshold();
error FactoryAlreadyRegistered();
error LMAlreadyRegistered();
error FactoryNotRegistered();
error LMNotRegistered();
error WithdrawingLockedEmissions();
constructor() {
_disableInitializers();
}
function initialize(ILiquidStabilityPool.InitParams calldata params) initializer external {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (address(params._metaCore) == address(0) || params._liquidationManager == address(0) || params._factory == address(0)) {
revert AddressZero();
}
$.metaCore = params._metaCore;
$.feeReceiver = params._feeReceiver;
_registerProtocol(
$,
address(params._liquidationManager),
address(params._factory)
);
// @dev At deployment there is no NECT oracle, will be added shortly after
// IPriceFeed priceFeed = IPriceFeed(params._metaCore.priceFeed());
// if (priceFeed.fetchPrice(address(params._asset)) == 0) revert NoPriceFeed();
__ERC20_init(params._sharesName, params._sharesSymbol);
__ERC4626_init(params._asset);
}
modifier onlyOwner {
_onlyOwner();
_;
}
modifier whenNotBootstrapPeriod() {
_whenNotBootstrapPeriod();
_;
}
function _onlyOwner() private view {
// Owner is beacon variable MetaCore::owner()
if (msg.sender != _getLSPStorage().metaCore.owner()) revert OnlyOwner();
}
function _whenNotBootstrapPeriod() internal view {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (
block.timestamp < $.metaCore.lspBootstrapPeriod()
) revert BootstrapPeriod();
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
function enableCollateral(address _collateral, uint64 _unlockRatePerSecond, bool forceThroughBalanceCheck) external {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (_collateral == asset()) revert TokenCannotBeDebtToken();
if (!$.factoryProtocol[msg.sender]) revert CallerNotFactory();
if ($.extraAssets.contains(_collateral)) revert TokenCannotBeExtraAsset();
uint length = $.collateralTokens.length;
bool collateralEnabled;
$.balanceData.setUnlockRatePerSecond(_collateral, _unlockRatePerSecond);
for (uint i; i < length; i++) {
if ($.collateralTokens[i] == _collateral) {
collateralEnabled = true;
break;
}
}
if (!collateralEnabled) {
ILiquidStabilityPool.Queue memory queueCached = $.queue;
if (
queueCached.nextSunsetIndexKey > queueCached.firstSunsetIndexKey
) {
ILiquidStabilityPool.SunsetIndex memory sIdx = $._sunsetIndexes[
queueCached.firstSunsetIndexKey
];
if (sIdx.expiry < block.timestamp) {
delete $._sunsetIndexes[$.queue.firstSunsetIndexKey++];
_overwriteCollateral(_collateral, sIdx.idx, forceThroughBalanceCheck);
return;
}
}
$.collateralTokens.push(_collateral);
$.indexByCollateral[_collateral] = $.collateralTokens.length;
} else {
bool isSunsetting = $.indexByCollateral[_collateral] == 0;
if (isSunsetting) {
revert CollateralIsSunsetting();
} else {
revert ExistingCollateral();
}
}
}
/// @dev When a collateral is overwritten it will stop being tracked on totalAssets and withdraws, a total rebalance is needed
function _overwriteCollateral(address _newCollateral, uint idx, bool forceThroughBalanceCheck) internal {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if($.indexByCollateral[_newCollateral] != 0) revert CollateralMustBeSunset();
address oldCollateral = $.collateralTokens[idx];
if ($.balanceData.balance[oldCollateral] != 0 && !forceThroughBalanceCheck) revert BalanceRemaining();
$.indexByCollateral[_newCollateral] = idx + 1;
$.collateralTokens[idx] = _newCollateral;
emit CollateralOverwritten(oldCollateral, _newCollateral);
}
/**
* @notice Starts sunsetting a collateral
* During sunsetting liquidated collateral handoff to the SP will revert
@dev IMPORTANT: When sunsetting a collateral, `PositionManager.startSunset`
should be called on all PM linked to that collateral
@param collateral Collateral to sunset
*/
function startCollateralSunset(address collateral) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if ($.indexByCollateral[collateral] == 0) revert CollateralIsSunsetting();
$._sunsetIndexes[$.queue.nextSunsetIndexKey++] = ILiquidStabilityPool.SunsetIndex(
uint128($.indexByCollateral[collateral] - 1),
uint128(block.timestamp + SUNSET_DURATION)
);
delete $.indexByCollateral[collateral];
}
/** @dev See {IERC4626-totalAssets}. */
/// @dev AmountInDebtToken is scaled to 18 decimals, since its DEBT_TOKEN decimals
/// @dev Substracts balances locked emissions
function totalAssets() public view override returns (uint amountInDebtToken) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
uint amountInUsd;
address[] memory collaterals = getCollateralTokens();
uint debtTokenPrice = getPrice(asset());
uint collateralsLength = collaterals.length;
uint extraAssetsLength = $.extraAssets.length();
// we directly use `$.balanceData.balance[]` instead of `$.balanceOf` because DEBT_TOKEN can't be an extra asset, neither a collateral, which are the only ones that can be locked through `addEmissions()`
// this comment applies to all instances of `$.balanceData.balance[asset()]`
// assumes DEBT_TOKEN is 18 decimals
uint debtTokenBalance = $.balanceData.balance[asset()];
for (uint i; i < collateralsLength; i++) {
address collateral = collaterals[i];
uint balance = $.balanceData.balanceOf(collateral);
if (balance > 0) {
amountInUsd += balance.convertToValue(getPrice(collateral), IAsset(collateral).decimals());
}
}
for (uint i; i < extraAssetsLength; i++) {
address token = $.extraAssets.at(i);
uint balance = $.balanceData.balanceOf(token);
if (balance > 0) {
amountInUsd += balance.convertToValue(getPrice(token), IAsset(token).decimals());
}
}
amountInDebtToken = amountInUsd * WAD / debtTokenPrice + debtTokenBalance;
}
function getPrice(
address token
) public view returns (uint scaledPriceInUsdWad) {
IPriceFeed priceFeed = IPriceFeed(_getLSPStorage().metaCore.priceFeed());
return priceFeed.fetchPrice(token);
}
function deposit(
uint assets,
address receiver
) public override returns (uint shares) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if ($.metaCore.paused()) revert Paused();
(uint rawShares, uint feeShares) = _previewDeposit(assets);
shares = rawShares - feeShares;
_depositAndMint($, shares, assets, receiver, feeShares);
}
function mint(
uint shares,
address receiver
) public override returns (uint assets) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if ($.metaCore.paused()) revert Paused();
assets = previewMint(shares);
uint fee = shares.mulDiv(BP, BP - _entryFeeBP(), Math.Rounding.Up) - shares;
_depositAndMint($, shares, assets, receiver, fee);
}
function _depositAndMint(ILiquidStabilityPool.LSPStorage storage $, uint shares, uint assets, address receiver, uint fee) private {
// Here we pass 'assets' since it is the amount of DebtToken we want to transfer to the LSP
_provideFromAccount(msg.sender, assets);
if (fee != 0) {
_mint($.feeReceiver, fee);
}
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
}
function withdraw(
uint assets,
address receiver,
address _owner
) public whenNotBootstrapPeriod override returns (uint shares) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
uint _totalSupply = totalSupply();
uint maxAssets = maxWithdraw(_owner);
if (assets > maxAssets) revert ERC4626ExceededMaxWithdraw(_owner, assets, maxAssets);
shares = previewWithdraw(assets);
(uint debtTokenAmount, uint fee) = _burn($, shares, _totalSupply, _owner);
_withdraw(debtTokenAmount, receiver, shares - fee, _totalSupply, _owner, assets, shares);
}
function redeem(
uint shares,
address receiver,
address _owner
) public whenNotBootstrapPeriod override returns (uint assets) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
uint _totalSupply = totalSupply();
uint maxShares = maxRedeem(_owner);
if (shares > maxShares) revert ERC4626ExceededMaxRedeem(_owner, shares, maxShares);
assets = previewRedeem(shares);
(uint debtTokenAmount, uint fee) = _burn($, shares, _totalSupply, _owner);
_withdraw(debtTokenAmount, receiver, shares - fee, _totalSupply, _owner, assets, shares);
}
function _withdraw(uint debtTokenAmount, address receiver, uint cachedShares, uint _totalSupply, address _owner, uint assets, uint shares) private {
_withdrawFromAccount(debtTokenAmount, receiver);
_withdrawCollAndExtraAssets(receiver, cachedShares, _totalSupply);
emit Withdraw(msg.sender, receiver, _owner, assets, shares);
}
function withdraw(
uint assets,
address[] calldata preferredUnderlyingTokens,
address receiver,
address _owner
) public whenNotBootstrapPeriod returns (uint shares) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
uint maxAssets = maxWithdraw(_owner);
if (assets > maxAssets) revert ERC4626ExceededMaxWithdraw(_owner, assets, maxAssets);
/// @dev should we have a check for assets == 0? its redundant but gas will be low
shares = previewWithdraw(assets);
// Pass totalSupply as 0 since we don't need to calculate `debtTokenAmount`
_burn($, shares, 0, _owner);
_withdrawPreferredUnderlying($, assets, preferredUnderlyingTokens, receiver);
emit Withdraw(msg.sender, receiver, _owner, assets, shares);
}
function redeem(
uint shares,
address[] calldata preferredUnderlyingTokens,
address receiver,
address _owner
) public whenNotBootstrapPeriod returns (uint assets) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
uint maxShares = maxRedeem(_owner);
if (shares > maxShares) revert ERC4626ExceededMaxRedeem(_owner, shares, maxShares);
assets = previewRedeem(shares);
// Pass totalSupply as 0 since we don't need to calculate `debtTokenAmount`
_burn($, shares, 0, _owner);
_withdrawPreferredUnderlying($, assets, preferredUnderlyingTokens, receiver);
emit Withdraw(msg.sender, receiver, _owner, assets, shares);
}
function _burn(ILiquidStabilityPool.LSPStorage storage $, uint shares, uint _totalSupply, address _owner) private returns (uint debtTokenAmount, uint fee) {
fee = shares.feeOnRaw(_exitFeeBP());
if (msg.sender != _owner) {
_spendAllowance(_owner, msg.sender, shares);
}
/// @dev Always round in favor of the vault
if (_totalSupply != 0) {
debtTokenAmount = (shares - fee).mulDiv($.balanceData.balance[asset()], _totalSupply, Math.Rounding.Down);
}
// We could remove fee > 0 if we deploy with fees and the minimum fee is not 0
if (fee != 0) {
_mint($.feeReceiver, fee);
}
_burn(_owner, shares);
}
/// @dev No token validation is needed, if token is not collateral or extraAsset, it will underflow in `$balance[token]`
/// @dev Reentrancy attack vector should not be possible since user has their shares burned before the calls to tokens
/// @dev No duplicated token check needed
function _withdrawPreferredUnderlying(
ILiquidStabilityPool.LSPStorage storage $,
uint assets,
address[] memory preferredUnderlyingTokens,
address receiver
) internal {
// Avoid stack too deep error
ILiquidStabilityPool.Arrays memory arr = _initArrays(preferredUnderlyingTokens);
if (arr.length != $.extraAssets.length() + arr.collateralsLength + 1) revert InvalidArrayLength();
if (!$.privilegedDebtRedeemers[msg.sender] && preferredUnderlyingTokens[arr.length - 1] != asset()) revert LastTokenMustBeDebtToken();
preferredUnderlyingTokens.checkForDuplicates(arr.length);
uint remainingAssets = assets;
uint debtTokenPrice = getPrice(asset());
for (uint i; i < arr.length && remainingAssets != 0; i++) {
address token = preferredUnderlyingTokens[i];
token.checkValidToken(arr.collaterals, arr.collateralsLength, asset(), $.extraAssets.contains(token));
uint unlockedBalance = $.balanceData.balanceOf(token);
if (unlockedBalance == 0) continue;
uint tokenPrice = getPrice(token);
// Price could be 0 if CollVault collateral or extraAsset is just added without atomical initial deposit
// Would result in less assets withdrawn than expected
if (tokenPrice == 0) continue;
uint8 tokenDecimals = IAsset(token).decimals();
uint256 amount;
if (token == asset()) {
// Avoid possible precision loss due to rounding in 'convertAssetsToCollAmount'
amount = remainingAssets;
} else {
amount = remainingAssets.convertAssetsToCollAmount(
tokenPrice,
debtTokenPrice,
decimals(), // DEBT_TOKEN decimals
tokenDecimals,
Math.Rounding.Down
);
}
if (unlockedBalance >= amount) {
remainingAssets = 0;
$.balanceData.balance[token] -= amount;
} else {
uint remainingColl = amount - unlockedBalance;
remainingAssets = remainingColl.convertCollAmountToAssets(
tokenPrice,
debtTokenPrice,
decimals(), // DEBT_TOKEN decimals
tokenDecimals
);
amount = unlockedBalance;
$.balanceData.balance[token] -= amount;
}
arr.amounts[i] = amount;
}
for (uint i; i < arr.length; i++) {
if(arr.amounts[i] > 0) {
IERC20(preferredUnderlyingTokens[i]).safeTransfer(receiver, arr.amounts[i]);
}
}
emit AssetsWithdraw(receiver, assets, preferredUnderlyingTokens, arr.amounts);
}
function _provideFromAccount(
address account,
uint _amount
) internal {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
IDebtToken(asset()).sendToSP(account, _amount);
$.balanceData.balance[asset()] += _amount;
}
function _withdrawFromAccount(
uint _amount,
address receiver
) internal {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
IDebtToken(asset()).returnFromPool(address(this), receiver, _amount);
$.balanceData.balance[asset()] -= _amount;
}
/*
* Cancels out the specified debt against the Debt contained in the Stability Pool (as far as possible)
*/
function offset(
address collateral,
uint _debtToOffset,
uint _collToAdd
) external virtual {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (!$.liquidationManagerProtocol[msg.sender]) revert CallerNotLM();
uint collPrice = getPrice(collateral);
uint debtTokenPrice = getPrice(asset());
uint debtInCollateralAmount = _debtToOffset.convertAssetsToCollAmount(
collPrice,
debtTokenPrice,
decimals(),
IAsset(collateral).decimals(),
Math.Rounding.Up
);
// Unlikely case in which LM offsets more debt value than collateral
uint collSurplusAmount;
if (_collToAdd > debtInCollateralAmount) {
collSurplusAmount = _collToAdd - debtInCollateralAmount;
}
if (collSurplusAmount > 0) {
$.balanceData.addEmissions(address(collateral), collSurplusAmount.toUint128());
}
$.balanceData.balance[collateral] += _collToAdd - collSurplusAmount;
// Cancel the liquidated Debt debt with the Debt in the stability pool
$.balanceData.balance[asset()] -= _debtToOffset;
emit Offset(collateral, _debtToOffset, _collToAdd, collSurplusAmount);
}
/**
* @notice Withdraws as much collaterals awaiting conversion as shares being used for DEBT_TOKEN withdrawal
* @param receiver Address to receive the collaterals
* @param shares Amount of shares being used for DEBT_TOKEN withdrawal
* @param _totalSupply Has shares added to total supply since they have just been burned
*/
function _withdrawCollAndExtraAssets(
address receiver,
uint shares,
uint _totalSupply
) internal {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
address[] memory collaterals = getCollateralTokens();
uint collLength = collaterals.length;
uint extraAssetsLength = $.extraAssets.length();
uint[] memory amounts = new uint[](collLength + extraAssetsLength);
address[] memory tokens = new address[](collLength + extraAssetsLength);
for (uint i; i < collLength; i++) {
uint balanceWithUnlockedEmissions = $.balanceData.balanceOf(collaterals[i]);
amounts[i] = shares.mulDiv(balanceWithUnlockedEmissions, _totalSupply, Math.Rounding.Down);
tokens[i] = collaterals[i];
$.balanceData.balance[collaterals[i]] -= amounts[i];
}
for (uint i; i < extraAssetsLength; i++) {
uint idx = i + collLength;
address token = $.extraAssets.at(i);
uint balanceWithUnlockedEmissions = $.balanceData.balanceOf(token);
amounts[idx] = shares.mulDiv(balanceWithUnlockedEmissions, _totalSupply, Math.Rounding.Down);
tokens[idx] = token;
$.balanceData.balance[token] -= amounts[idx];
}
for (uint i; i < tokens.length; i++) {
if (amounts[i] != 0) {
IERC20(tokens[i]).safeTransfer(receiver, amounts[i]);
}
}
emit AssetsWithdraw(receiver, shares, tokens, amounts);
}
function rebalance(ILiquidStabilityPool.RebalanceParams calldata p) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (p.sentCurrency == p.receivedCurrency) revert SameTokens();
uint sentPrice = getPrice(p.sentCurrency);
uint receivedPrice = getPrice(p.receivedCurrency);
uint8 sentDecimals = IAsset(p.sentCurrency).decimals();
uint8 receivedDecimals = IAsset(p.receivedCurrency).decimals();
uint sentCurrencyBalance = IAsset(p.sentCurrency).balanceOf(address(this));
uint receivedCurrencyBalance = IAsset(p.receivedCurrency).balanceOf(address(this));
// Perform the swap using the swapper contract
IERC20(p.sentCurrency).safeTransfer(p.swapper, p.sentAmount);
IRebalancer(p.swapper).swap(
p.sentCurrency,
p.sentAmount,
p.receivedCurrency,
p.payload
);
uint received = IAsset(p.receivedCurrency).balanceOf(address(this)) - receivedCurrencyBalance;
uint sent = sentCurrencyBalance - IAsset(p.sentCurrency).balanceOf(address(this));
// if we were to rebalance locked emissions, a possible revert on subsequent `$.balanceOf` calls would occur
if (sent > $.balanceData.balance[p.sentCurrency] - getLockedEmissions(p.sentCurrency)) revert WithdrawingLockedEmissions();
uint receivedValue = received.convertToValue(receivedPrice, receivedDecimals);
uint sentValue = sent.convertToValue(sentPrice, sentDecimals);
bytes32 hash = keccak256(abi.encodePacked(p.sentCurrency, p.receivedCurrency));
// if threshold isn't set, it will be 0, not tolerating any slippage
if (receivedValue < sentValue * (BP - $.threshold[hash]) / BP) revert BelowThreshold();
$.balanceData.balance[p.sentCurrency] -= sent;
$.balanceData.balance[p.receivedCurrency] += received;
emit Rebalance(p.sentCurrency, p.receivedCurrency, sent, received, sentValue, receivedValue);
}
/**
* @dev Limited to tokens that are not collaterals or DEBT_TOKEN
* @param token Token to add to the extraAssets
* @param _unlockRatePerSecond Unlock rate per second once the token is pulled to the LSP
*/
function addNewExtraAsset(
address token,
uint64 _unlockRatePerSecond
) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
address[] memory collaterals = getCollateralTokens();
if (token == asset()) revert TokenCannotBeDebtToken();
uint enableCollateralLength = collaterals.length;
for (uint i; i < enableCollateralLength; i++) {
if (collaterals[i] == token) revert ExistingCollateral();
}
if (!$.extraAssets.add(token)) revert TokenCannotBeExtraAsset();
IPriceFeed priceFeed = IPriceFeed($.metaCore.priceFeed());
if (priceFeed.fetchPrice(token) == 0) revert NoPriceFeed();
$.balanceData.setUnlockRatePerSecond(token, _unlockRatePerSecond);
emit ExtraAssetAdded(token);
}
/*
* @notice Params overwrites the current vesting for the token
* @dev Adjust the unlockRatePerSecond if we want to keep the fullUnlockTimestamp
*/
function linearVestingExtraAssets(address token, int amount, address recipient) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (totalSupply() == 0) revert ZeroTotalSupply(); // convertToShares will return 0 for 'assets < totalAssets'
if (!$.extraAssets.contains(token)) revert TokenMustBeExtraAsset();
if (amount > 0) {
uint _amount = uint(amount);
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
$.balanceData.addEmissions(token, _amount.toUint128());
} else {
uint _amount = uint(-amount);
// Note, revert with underflow if amount > `lockedEmissions`
$.balanceData.subEmissions(token, _amount.toUint128());
IERC20(token).safeTransfer(recipient, _amount);
}
}
function removeExtraAsset(address token) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if ($.balanceData.balance[token] != 0) revert BalanceRemaining();
if ($.balanceData.emissionSchedule[token].unlockTimestamp() >= block.timestamp) revert TokenIsVesting();
if (!$.extraAssets.remove(token)) revert TokenMustBeExtraAsset();
emit ExtraAssetRemoved(token);
}
function setPairThreshold(address tokenIn, address tokenOut, uint thresholdInBP) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (thresholdInBP > BP) revert InvalidThreshold();
bytes32 hash = keccak256(abi.encodePacked(tokenIn, tokenOut));
$.threshold[hash] = thresholdInBP;
}
function setUnlockRatePerSecond(address token, uint64 _unlockRatePerSecond) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
$.balanceData.setUnlockRatePerSecond(token, _unlockRatePerSecond);
}
function setPrivilegedDebtRedeemers(address[] calldata redeemers, bool[] calldata enables) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (redeemers.length != enables.length) revert InvalidArrayLength();
for (uint i; i < redeemers.length; i++) {
$.privilegedDebtRedeemers[redeemers[i]] = enables[i];
}
}
// Preview ERC4626 functions applying entry/exit fees
function previewDeposit(uint assets) public view override returns (uint) {
(uint rawShares, uint feeShares) = _previewDeposit(assets);
return rawShares - feeShares;
}
function _previewDeposit(uint assets) internal view returns (uint rawShares, uint feeShares) {
rawShares = super.previewDeposit(assets);
feeShares = rawShares.feeOnRaw(_entryFeeBP());
}
function previewMint(uint netShares) public view override returns (uint) {
uint totalShares = netShares.mulDiv(BP, BP - _entryFeeBP(), Math.Rounding.Up);
return super.previewMint(totalShares);
}
function previewWithdraw(uint assets) public view override returns (uint) {
uint netShares = super.previewWithdraw(assets);
uint totalShares = netShares.mulDiv(BP, BP - _exitFeeBP(), Math.Rounding.Up);
return totalShares;
}
function previewRedeem(uint shares) public view override returns (uint) {
uint fee = shares.feeOnRaw(_exitFeeBP());
return super.previewRedeem(shares - fee);
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address _owner) public view override returns (uint) {
return previewRedeem(balanceOf(_owner));
}
// === Fee configuration ===
/// @dev Rebalancer fee discounts will look to a forwarding contract similar to LSPRouter, but with access control
function _entryFeeBP() internal view virtual returns (uint) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
return $.metaCore.getLspEntryFee(msg.sender);
}
function _exitFeeBP() internal view virtual returns (uint) {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
return $.metaCore.getLspExitFee(msg.sender);
}
function _initArrays(address[] memory preferredUnderlyingTokens) private view returns (ILiquidStabilityPool.Arrays memory arr) {
address[] memory collaterals = getCollateralTokens();
uint length = preferredUnderlyingTokens.length;
arr = ILiquidStabilityPool.Arrays({
length: length,
collaterals: collaterals,
collateralsLength: collaterals.length,
amounts: new uint[](length)
});
}
/// @notice Either registeres or blacklists a protocol from using the LSP by setting/removing its factory and liquidation manager permissions
/// @param _factory The factory contract address to update
/// @param _liquidationManager The liquidation manager contract address to update
function updateProtocol(
address _liquidationManager,
address _factory,
bool _register
) external onlyOwner {
ILiquidStabilityPool.LSPStorage storage $ = _getLSPStorage();
if (
_liquidationManager == address(0) ||
_factory == address(0)
) revert AddressZero();
if (_register) {
_registerProtocol($, _liquidationManager, _factory);
} else {
if (!$.factoryProtocol[_factory]) revert FactoryNotRegistered();
if (!$.liquidationManagerProtocol[_liquidationManager]) revert LMNotRegistered();
delete $.factoryProtocol[_factory];
delete $.liquidationManagerProtocol[_liquidationManager];
emit ProtocolBlacklisted(_factory, _liquidationManager);
}
}
function _registerProtocol(
ILiquidStabilityPool.LSPStorage storage $,
address _liquidationManager,
address _factory
) internal {
if ($.factoryProtocol[_factory]) revert FactoryAlreadyRegistered();
if ($.liquidationManagerProtocol[_liquidationManager]) revert LMAlreadyRegistered();
$.factoryProtocol[_factory] = true;
$.liquidationManagerProtocol[_liquidationManager] = true;
emit ProtocolRegistered(_factory, _liquidationManager);
}
/* STORAGE VIEW */
function extSloads(bytes32[] calldata slots) external view returns (bytes32[] memory res) {
uint nSlots = slots.length;
res = new bytes32[](nSlots);
for (uint i; i < nSlots;) {
bytes32 slot = slots[i++];
assembly ("memory-safe") {
mstore(add(res, mul(i, 32)), sload(slot))
}
}
}
/// @dev Returns the locked emissions
function getLockedEmissions(address token) public view returns (uint) {
EmissionsLib.EmissionSchedule memory schedule = _getLSPStorage().balanceData.emissionSchedule[token];
uint fullUnlockTimestamp = schedule.unlockTimestamp();
return schedule.lockedEmissions(fullUnlockTimestamp);
}
/**
* @notice DEBT_TOKEN is not locked
*/
function getTotalDebtTokenDeposits() external view returns (uint) {
return _getLSPStorage().balanceData.balance[asset()];
}
/**
* @dev Tracks Stability's Pool `collateralTokens`
* `collateralTokens` is pushed when a new collateral is added, but its index are overwritten if coll didn't exist
* When a sunset is expired, its epoch is set to 0, and a new coll is added at that index
* `queue.first` is increased for every sunsetted expired coll that is overwritten
* `queue.next` is increased for every coll sunset, and it stores the index of the coll being sunset of the `collateralTokens` array
* because the sunsetted expired collateral is only removed from the `collateralTokens` array when a new coll is added, the pulling of the coll has to check the sunset isn't expired
* TLDR; the function doesn't need changes but the pulling of the coll has to check the sunset isn't expired
*/
/// The comments below is to handle the case when a sunset collateral expires and is not yet overwritten on the LSP::collateralTokens array
/// @dev My stance on this matter is that it is possible that certain balance liquidated collateral can happen to stoy at LV after its sunset expires
/// On that case we could whitelist it to overwrite it and remove it from the LSP::collateralTokens array
/// Doing that we could add it as extraAsset token (it no longer is in coll array)
/// But whitelisting would require a new token, which we may not have the need to add as collateral type
/// I'm a fan of dynamically excluding it below once the sunset expires and manually adding it as extraAsset token if it makes sense economically
function getCollateralTokens() public view returns (address[] memory) {
return _getLSPStorage().collateralTokens;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
* The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
* and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
* itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
* offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
* of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
* With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
* underlying math can be found xref:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*/
abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626 {
using Math for uint256;
/// @custom:storage-location erc7201:openzeppelin.storage.ERC4626
struct ERC4626Storage {
IERC20 _asset;
uint8 _underlyingDecimals;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC4626")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC4626StorageLocation = 0x0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00;
function _getERC4626Storage() private pure returns (ERC4626Storage storage $) {
assembly {
$.slot := ERC4626StorageLocation
}
}
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
*/
function __ERC4626_init(IERC20 asset_) internal onlyInitializing {
__ERC4626_init_unchained(asset_);
}
function __ERC4626_init_unchained(IERC20 asset_) internal onlyInitializing {
ERC4626Storage storage $ = _getERC4626Storage();
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
$._underlyingDecimals = success ? assetDecimals : 18;
$._asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeCall(IERC20Metadata.decimals, ())
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20Metadata, ERC20Upgradeable) returns (uint8) {
ERC4626Storage storage $ = _getERC4626Storage();
return $._underlyingDecimals + _decimalsOffset();
}
/** @dev See {IERC4626-asset}. */
function asset() public view virtual returns (address) {
ERC4626Storage storage $ = _getERC4626Storage();
return address($._asset);
}
/** @dev See {IERC4626-totalAssets}. */
function totalAssets() public view virtual returns (uint256) {
ERC4626Storage storage $ = _getERC4626Storage();
return $._asset.balanceOf(address(this));
}
/** @dev See {IERC4626-convertToShares}. */
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Down);
}
/** @dev See {IERC4626-convertToAssets}. */
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Down);
}
/** @dev See {IERC4626-maxDeposit}. */
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxMint}. */
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Down);
}
/** @dev See {IERC4626-maxRedeem}. */
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Down);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Up);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Up);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Down);
}
/** @dev See {IERC4626-deposit}. */
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/** @dev See {IERC4626-mint}. */
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/** @dev See {IERC4626-withdraw}. */
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/** @dev See {IERC4626-redeem}. */
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
ERC4626Storage storage $ = _getERC4626Storage();
// If _asset is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20.safeTransferFrom($._asset, caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
ERC4626Storage storage $ = _getERC4626Storage();
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If _asset is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20.safeTransfer($._asset, receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
* @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.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @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._indexes[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 read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 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 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
library PriceLib {
using Math for uint;
// WAD adjusted result
function convertToValue(uint amount, uint price, uint8 decimals) internal pure returns (uint) {
return amount * price / 10 ** decimals;
}
function convertToAmount(uint amountInUsd, uint collPrice, uint8 collDecimals, Math.Rounding rounding) internal pure returns (uint) {
if (collPrice == 0 || amountInUsd == 0) {
return 0;
}
return amountInUsd.mulDiv(10 ** collDecimals, collPrice, rounding);
}
// Coll decimal adjust amount result
function convertAssetsToCollAmount(uint assets, uint collPrice, uint debtTokenPrice, uint8 vaultDecimals, uint8 collDecimals, Math.Rounding rounding) internal pure returns (uint) {
uint assetsUsdValue = assets.mulDiv(debtTokenPrice, 10 ** vaultDecimals, rounding);
if (collPrice != 0) {
return convertToAmount(assetsUsdValue, collPrice, collDecimals, rounding);
} else {
return 0;
}
}
function convertCollAmountToAssets(uint collAmount, uint collPrice, uint debtTokenPrice, uint8 vaultDecimals, uint8 collDecimals) internal pure returns (uint) {
uint collUsdValue = collAmount * collPrice / 10 ** collDecimals;
if (debtTokenPrice != 0) {
return collUsdValue * 10 ** vaultDecimals / debtTokenPrice;
} else {
return 0;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {DynamicArrayLib} from "solady/utils/DynamicArrayLib.sol";
import {IInfraredCollateralVault} from "src/interfaces/core/vaults/IInfraredCollateralVault.sol";
library TokenValidationLib {
using DynamicArrayLib for DynamicArrayLib.DynamicArray;
using DynamicArrayLib for address[];
using DynamicArrayLib for uint[];
error DuplicateToken();
error InvalidToken();
function checkForDuplicates(address[] memory tokens, uint length) internal pure {
for (uint i; i < length; i++) {
for (uint j = i + 1; j < length; j++) {
if (tokens[i] == tokens[j]) revert DuplicateToken();
}
}
}
function checkValidToken(address token, address[] memory collaterals, uint collateralsLength, address debtToken, bool isExtraAsset) internal pure {
if (isExtraAsset || token == debtToken) {
return;
}
bool isCollateral;
for (uint j; j < collateralsLength; j++) {
if (collaterals[j] == token) {
isCollateral = true;
break;
}
}
if (!isCollateral) revert InvalidToken();
}
function aggregateIfNotExistent(
address token,
uint amount,
DynamicArrayLib.DynamicArray memory tokens,
DynamicArrayLib.DynamicArray memory amounts
) internal pure {
uint index = tokens.indexOf(token);
if (index != DynamicArrayLib.NOT_FOUND) {
uint existingAmount = amounts.getUint256(index);
amounts.set(index, existingAmount + amount);
} else {
tokens.p(token);
amounts.p(amount);
}
}
function contains(address[] memory tokenArray, address targetToken) internal pure returns (uint256) {
uint256 length = tokenArray.length;
for (uint256 i; i < length; ++i) {
if (tokenArray[i] == targetToken) {
return i + 1;
}
}
return 0;
}
/// @dev If the ibgtVault is included in the rewardTokens list, it returns a new reward array that includes the rewardToken list from the ibgtVault.
function tryGetRewardedTokensIncludingIbgtVault(
address[] memory rewardTokens,
address collVaultAsset,
IInfraredCollateralVault ibgtVault
) internal view returns (address[] memory, uint256) {
// Gets a new rewardToken array that includes collVaultAsset.
(address[] memory newRewardTokens, uint256 length) = pushIfNotIncluded(rewardTokens, collVaultAsset);
uint256 ibgtVaultIdx = contains(newRewardTokens, address(ibgtVault));
// returns when ibgtVault is not included in rewardTokens array
if(ibgtVaultIdx == 0) {
return (newRewardTokens, length);
}
// replace ibgtVault with ibgt
newRewardTokens[ibgtVaultIdx - 1] = ibgtVault.asset();
address[] memory ibgtVaultRewardTokens = tryGetRewardedTokens(ibgtVault);
if(ibgtVaultRewardTokens.length == 0) {
return (newRewardTokens, length);
}
// finalRewardTokens length shouldn't be bigger than (length + ibgtVaultLength)
uint256 ibgtVaultLength = ibgtVaultRewardTokens.length;
address[] memory finalRewardTokens = new address[](length + ibgtVaultLength);
uint256 finalLength;
// Merge two arrays using the union set method
for(uint256 i; i < length; ++i) {
if(contains(ibgtVaultRewardTokens, newRewardTokens[i]) == 0) {
finalRewardTokens[finalLength] = newRewardTokens[i];
++finalLength;
}
}
for(uint256 i; i < ibgtVaultLength; ++i) {
finalRewardTokens[finalLength] = ibgtVaultRewardTokens[i];
++finalLength;
}
assembly {
mstore(finalRewardTokens, finalLength)
}
return (finalRewardTokens, finalLength);
}
/// @dev Checks if asset is included in reward tokens array (e.g. BBiBGT)
/// @dev CollVault main asset goes at index (len - 1), if it is not included in reward tokens
/// @dev The ordering is inlined with the `CollVaultRouter::previewRedeemUnderlying()` function
function pushIfNotIncluded(address[] memory rewardTokens, address collVaultAsset)
internal
pure
returns (address[] memory, uint256)
{
uint256 originalLength = rewardTokens.length;
if (contains(rewardTokens, collVaultAsset) > 0) {
return (rewardTokens, originalLength);
}
address[] memory _rewardTokens = new address[](originalLength + 1);
for (uint i; i < originalLength; ++i) {
_rewardTokens[i] = rewardTokens[i];
}
_rewardTokens[originalLength] = collVaultAsset;
return (_rewardTokens, originalLength + 1);
}
/// @dev Vaults in LSP could still not have been upgrade to InfraredCollateralVault if there is no InfraredVault to earn PoL deployed yet
function tryGetRewardedTokens(IInfraredCollateralVault collVault) internal view returns (address[] memory) {
address[] memory rewardedTokens;
try collVault.rewardedTokens() returns (address[] memory _rewardedTokens) {
rewardedTokens = _rewardedTokens;
} catch {}
return rewardedTokens;
}
function underlyingAmounts(address[] memory tokens, address account) internal view returns (uint[] memory amounts) {
amounts = new uint[](tokens.length);
for (uint i; i < tokens.length; i++) {
amounts[i] = IERC20(tokens[i]).balanceOf(account);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {ILiquidStabilityPool} from "../interfaces/core/ILiquidStabilityPool.sol";
library EmissionsLib {
using SafeCast for uint256;
uint64 constant internal DEFAULT_UNLOCK_RATE = 1e11; // 10% per second
uint64 constant internal MAX_UNLOCK_RATE = 1e12; // 100%
struct BalanceData {
mapping(address token => uint) balance;
mapping(address token => EmissionSchedule) emissionSchedule;
}
struct EmissionSchedule {
uint128 emissions;
uint64 lockTimestamp;
uint64 _unlockRatePerSecond; // rate points
}
error AmountCannotBeZero();
error EmissionRateExceedsMax();
// error UnsupportedEmissionConfig();
event EmissionsAdded(address indexed token, uint128 amount);
event EmissionsSub(address indexed token, uint128 amount);
event NewUnlockRatePerSecond(address indexed token, uint64 unlockRatePerSecond);
/// @dev zero _unlockRatePerSecond parameter resets rate back to DEFAULT_UNLOCK_RATE
function setUnlockRatePerSecond(BalanceData storage $, address token, uint64 _unlockRatePerSecond) internal {
if (_unlockRatePerSecond > MAX_UNLOCK_RATE) revert EmissionRateExceedsMax();
_addEmissions($, token, 0); // update lockTimestamp and emissions
$.emissionSchedule[token]._unlockRatePerSecond = _unlockRatePerSecond;
emit NewUnlockRatePerSecond(token, _unlockRatePerSecond);
}
function addEmissions(BalanceData storage $, address token, uint128 amount) internal {
if (amount == 0) revert AmountCannotBeZero();
_addEmissions($, token, amount);
emit EmissionsAdded(token, amount);
}
function _addEmissions(BalanceData storage $, address token, uint128 amount) private {
EmissionSchedule memory schedule = $.emissionSchedule[token];
uint256 _unlockTimestamp = unlockTimestamp(schedule);
uint128 nextEmissions = (lockedEmissions(schedule, _unlockTimestamp) + amount).toUint128();
schedule.emissions = nextEmissions;
schedule.lockTimestamp = block.timestamp.toUint64();
$.balance[token] += amount;
$.emissionSchedule[token] = schedule;
}
function subEmissions(BalanceData storage $, address token, uint128 amount) internal {
if (amount == 0) revert AmountCannotBeZero();
_subEmissions($, token, amount);
emit EmissionsSub(token, amount);
}
function _subEmissions(BalanceData storage $, address token, uint128 amount) private {
EmissionSchedule memory schedule = $.emissionSchedule[token];
uint256 _unlockTimestamp = unlockTimestamp(schedule);
uint128 nextEmissions = (lockedEmissions(schedule, _unlockTimestamp) - amount).toUint128();
schedule.emissions = nextEmissions;
schedule.lockTimestamp = block.timestamp.toUint64();
$.balance[token] -= amount;
$.emissionSchedule[token] = schedule;
}
/// @dev Doesn't include locked emissions
function unlockedEmissions(EmissionSchedule memory schedule) internal view returns (uint256) {
return schedule.emissions - lockedEmissions(schedule, unlockTimestamp(schedule));
}
function balanceOfWithFutureEmissions(BalanceData storage $, address token) internal view returns (uint256) {
return $.balance[token];
}
/**
* @notice Returns the unlocked token emissions
*/
function balanceOf(BalanceData storage $, address token) internal view returns (uint256) {
EmissionSchedule memory schedule = $.emissionSchedule[token];
return $.balance[token] - lockedEmissions(schedule, unlockTimestamp(schedule));
}
/**
* @notice Returns locked emissions
*/
function lockedEmissions(EmissionSchedule memory schedule, uint256 _unlockTimestamp) internal view returns (uint256) {
if (block.timestamp >= _unlockTimestamp) {
// all emissions were unlocked
return 0;
} else {
// emissions are still unlocking, calculate the amount of already unlocked emissions
uint256 secondsSinceLockup = block.timestamp - schedule.lockTimestamp;
// design decision - use dimensionless 'unlock rate units' to unlock emissions over a fixed time window
uint256 ratePointsUnlocked = unlockRatePerSecond(schedule) * secondsSinceLockup;
// emissions remainder is designed to be added to balance in unlockTimestamp
return schedule.emissions - ratePointsUnlocked * schedule.emissions / MAX_UNLOCK_RATE;
}
}
// timestamp at which all emissions are fully unlocked
function unlockTimestamp(EmissionSchedule memory schedule) internal pure returns (uint256) {
// ceil to account for remainder seconds left after integer division
return divRoundUp(MAX_UNLOCK_RATE, unlockRatePerSecond(schedule)) + schedule.lockTimestamp;
}
function unlockRatePerSecond(EmissionSchedule memory schedule) internal pure returns (uint256) {
return schedule._unlockRatePerSecond == 0 ? DEFAULT_UNLOCK_RATE : schedule._unlockRatePerSecond;
}
function divRoundUp(uint256 dividend, uint256 divisor) internal pure returns (uint256) {
return (dividend + divisor - 1) / divisor;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
library FeeLib {
using Math for uint;
uint private constant BP = 1e4;
/// @dev Calculates the fees that should be added to an amount `shares` that does already include fees.
/// Used in {IERC4626-deposit}, {IERC4626-mint}, {IERC4626-withdraw} and {IERC4626-previewRedeem} operations.
function feeOnRaw(
uint shares,
uint feeBP
) internal pure returns (uint) {
return shares.mulDiv(feeBP, BP, Math.Rounding.Up);
}
/// @dev Calculates the fee part of an amount `shares` that deoes not includes fees.
/// Used in {IERC4626-previewDeposit} and {IERC4626-previewRedeem} operations.
function feeOnTotal(
uint shares,
uint feeBP
) internal pure returns (uint) {
return shares.mulDiv(feeBP, feeBP + BP, Math.Rounding.Up);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
library PropMath {
uint256 internal constant DECIMAL_PRECISION = 1e18;
/* Precision for Nominal ICR (independent of price). Rationale for the value:
*
* - Making it “too high” could lead to overflows.
* - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
*
* This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,
* and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
*
*/
uint256 internal constant NICR_PRECISION = 1e20;
function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a < _b) ? _a : _b;
}
function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a >= _b) ? _a : _b;
}
/*
* Multiply two decimal numbers and use normal rounding rules:
* -round product up if 19'th mantissa digit >= 5
* -round product down if 19'th mantissa digit < 5
*
* Used only inside the exponentiation, _decPow().
*/
function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {
uint256 prod_xy = x * y;
decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;
}
/*
* _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
*
* Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
*
* Called by two functions that represent time in units of minutes:
* 1) PositionManager._calcDecayedBaseRate
* 2) CommunityIssuance._getCumulativeIssuanceFraction
*
* The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
* "minutes in 1000 years": 60 * 24 * 365 * 1000
*
* If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
* negligibly different from just passing the cap, since:
*
* In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
* In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
*/
function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {
if (_minutes > 525600000) {
_minutes = 525600000;
} // cap to avoid overflow
if (_minutes == 0) {
return DECIMAL_PRECISION;
}
uint256 y = DECIMAL_PRECISION;
uint256 x = _base;
uint256 n = _minutes;
// Exponentiation-by-squaring
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n / 2;
} else {
// if (n % 2 != 0)
y = decMul(x, y);
x = decMul(x, x);
n = (n - 1) / 2;
}
}
return decMul(x, y);
}
function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a >= _b) ? _a - _b : _b - _a;
}
function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
if (_debt > 0) {
return (_coll * NICR_PRECISION) / _debt;
}
// Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
else {
// if (_debt == 0)
return 2 ** 256 - 1;
}
}
function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {
if (_debt > 0) {
uint256 newCollRatio = (_coll * _price) / _debt;
return newCollRatio;
}
// Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
else {
// if (_debt == 0)
return 2 ** 256 - 1;
}
}
function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
if (_debt > 0) {
uint256 newCollRatio = (_coll) / _debt;
return newCollRatio;
}
// Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
else {
// if (_debt == 0)
return 2 ** 256 - 1;
}
}
function _isApproxEqAbs(uint256 a, uint256 b, uint256 tolerance) internal pure returns (bool) {
return a > b ? (a - b) <= tolerance : (b - a) <= tolerance;
}
function _isWithinToleranceAbove(
uint256 a,
uint256 b,
uint256 tolerance
) internal pure returns (bool) {
if (a < b) return false;
return (a - b) <= tolerance;
}
function _isWithinToleranceBelow(
uint256 a,
uint256 b,
uint256 tolerance
) internal pure returns (bool) {
if (a > b) return false;
return (b - a) <= tolerance;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IMetaCore} from "./IMetaCore.sol";
import {IDebtToken} from "./IDebtToken.sol";
import {IDebtToken} from "./IDebtToken.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";
interface ILiquidStabilityPool is IERC4626, IERC1822Proxiable {
struct LSPStorage {
IMetaCore metaCore;
address feeReceiver;
/// @notice Array of tokens that have been emitted to the LiquidStabilityPool
/// @notice Used to track which tokens can be withdrawn to LSP share holders
/// @dev Doesn't include tokens that are already collaterals
EnumerableSet.AddressSet extraAssets;
Queue queue;
address[] collateralTokens;
mapping(uint16 => SunsetIndex) _sunsetIndexes;
mapping(address collateral => uint256 index) indexByCollateral;
mapping(bytes32 => uint) threshold;
EmissionsLib.BalanceData balanceData;
mapping(address => bool) factoryProtocol;
mapping(address => bool) liquidationManagerProtocol;
mapping(address => bool) privilegedDebtRedeemers;
}
struct InitParams {
IERC20 _asset;
string _sharesName;
string _sharesSymbol;
IMetaCore _metaCore;
address _liquidationManager;
address _factory;
address _feeReceiver;
}
struct RebalanceParams {
address sentCurrency;
uint sentAmount;
address receivedCurrency;
address swapper;
bytes payload;
}
struct SunsetIndex {
uint128 idx;
uint128 expiry;
}
struct Queue {
uint16 firstSunsetIndexKey;
uint16 nextSunsetIndexKey;
}
event CollAndEmissionsWithdraw(
address indexed receiver,
uint shares,
uint[] amounts
);
struct Arrays {
uint length;
address[] collaterals;
uint collateralsLength;
uint[] amounts;
}
event EmissionTokenAdded(address token);
event EmissionTokenRemoved(address token);
event StabilityPoolDebtBalanceUpdated(uint256 newBalance);
event UserDepositChanged(address indexed depositor, uint256 newDeposit);
event CollateralOverwritten(address oldCollateral, address newCollateral);
// PROXY
function upgradeToAndCall(address newImplementation, bytes calldata data) external;
function getCurrentImplementation() external view returns (address);
function SUNSET_DURATION() external view returns (uint128);
function totalDebtTokenDeposits() external view returns (uint256);
function enableCollateral(address _collateral, uint64 _unlockRatePerSecond, bool forceThroughBalanceCheck) external;
function startCollateralSunset(address collateral) external;
function getTotalDebtTokenDeposits() external view returns (uint256);
function getCollateralTokens() external view returns (address[] memory);
function offset(address collateral, uint256 _debtToOffset, uint256 _collToAdd) external;
function initialize(InitParams calldata params) external;
function rebalance(RebalanceParams calldata p) external;
function linearVestingExtraAssets(address token, int amount, address recipient) external;
function withdraw(
uint assets,
address[] calldata preferredUnderlyingTokens,
address receiver,
address _owner
) external returns (uint shares);
function redeem(
uint shares,
address[] calldata preferredUnderlyingTokens,
address receiver,
address _owner
) external returns (uint assets);
function updateProtocol(
address _liquidationManager,
address _factory,
bool _register
) external;
function redeem(
uint assets,
address receiver
) external returns (uint shares);
function addNewExtraAsset(address token, uint64 _unlockRatePerSecond) external;
function removeEmitedTokens(address token) external;
function setPairThreshold(address tokenIn, address tokenOut, uint thresholdInBP) external;
function setUnlockRatePerSecond(address token, uint64 _unlockRatePerSecond) external;
function getPrice(address token) external view returns (uint);
function getLockedEmissions(address token) external view returns (uint);
function extSloads(bytes32[] calldata slots) external view returns (bytes32[] memory res);
function unlockRatePerSecond(address token) external view returns (uint);
function removeExtraAsset(address token) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPriceFeed {
struct FeedType {
address spotOracle;
bool isCollVault;
}
event NewOracleRegistered(address token, address chainlinkAggregator, address underlyingDerivative);
event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);
event PriceRecordUpdated(address indexed token, uint256 _price);
event NewCollVaultRegistered(address collVault, bool enable);
event NewSpotOracleRegistered(address token, address spotOracle);
function fetchPrice(address _token) external view returns (uint256);
function getMultiplePrices(address[] memory _tokens) external view returns (uint256[] memory prices);
function setOracle(
address _token,
address _chainlinkOracle,
uint32 _heartbeat,
uint16 _staleThreshold,
address underlyingDerivative
) external;
function whitelistCollateralVault(address _collateralVaultShareToken, bool enable) external;
function setSpotOracle(address _token, address _spotOracle) external;
function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);
function CORE() external view returns (address);
function RESPONSE_TIMEOUT() external view returns (uint256);
function TARGET_DIGITS() external view returns (uint256);
function guardian() external view returns (address);
function oracleRecords(
address
)
external
view
returns (
address chainLinkOracle,
uint8 decimals,
uint32 heartbeat,
uint16 staleThreshold,
address underlyingDerivative
);
function isCollVault(address _collateralVaultShareToken) external view returns (bool);
function isStableBPT(address _oracle) external view returns (bool);
function isWeightedBPT(address _oracle) external view returns (bool);
function getSpotOracle(address _token) external view returns (address);
function feedType(address _token) external view returns (FeedType memory);
function owner() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC3156FlashBorrower } from "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol";
import "./ICore.sol";
interface IDebtToken is IERC20 {
// --- Events ---
event FlashLoanFeeUpdated(uint256 newFee);
// --- Public constants ---
function version() external view returns (string memory);
function permitTypeHash() external view returns (bytes32);
// --- Public immutables ---
function gasPool() external view returns (address);
function DEBT_GAS_COMPENSATION() external view returns (uint256);
// --- Public mappings ---
function liquidStabilityPools(address) external view returns (bool);
function borrowerOperations(address) external view returns (bool);
function factories(address) external view returns (bool);
function peripheries(address) external view returns (bool);
function positionManagers(address) external view returns (bool);
// --- External functions ---
function enablePositionManager(address _positionManager) external;
function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);
function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
function decimals() external view returns (uint8);
function sendToPeriphery(address _sender, uint256 _amount) external;
function sendToSP(address _sender, uint256 _amount) external;
function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function maxFlashLoan(address token) external view returns (uint256);
function flashFee(address token, uint256 amount) external view returns (uint256);
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
function whitelistLiquidStabilityPoolAddress(address _liquidStabilityPool, bool active) external;
function whitelistBorrowerOperationsAddress(address _borrowerOperations, bool active) external;
function whitelistFactoryAddress(address _factory, bool active) external;
function whitelistPeripheryAddress(address _periphery, bool active) external;
function whitelistPSM(address, bool) external;
function setDebtGasCompensation(uint256 _gasCompensation, bool _isFinalValue) external;
function setFlashLoanFee(uint256 _fee) external;
function DOMAIN_SEPARATOR() external view returns (bytes32);
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IMetaCore} from "src/interfaces/core/IMetaCore.sol";
interface ICore {
// --- Public variables ---
function metaCore() external view returns (IMetaCore);
function startTime() external view returns (uint256);
function CCR() external view returns (uint256);
function dmBootstrapPeriod() external view returns (uint64);
function isPeriphery(address peripheryContract) external view returns (bool);
// --- External functions ---
function setPeripheryEnabled(address _periphery, bool _enabled) external;
function setPMBootstrapPeriod(address dm, uint64 _bootstrapPeriod) external;
function setNewCCR(uint256 _CCR) external;
function priceFeed() external view returns (address);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function guardian() external view returns (address);
function feeReceiver() external view returns (address);
function paused() external view returns (bool);
function lspBootstrapPeriod() external view returns (uint64);
function getLspEntryFee(address rebalancer) external view returns (uint16);
function getLspExitFee(address rebalancer) external view returns (uint16);
function interestProtocolShare() external view returns (uint16);
function defaultInterestReceiver() external view returns (address);
// --- Events ---
event CCRSet(uint256 initialCCR);
event PMBootstrapPeriodSet(address dm, uint64 bootstrapPeriod);
event PeripheryEnabled(address indexed periphery, bool enabled);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface IRebalancer {
function swap(
address sentCurrency,
uint sentAmount,
address receivedCurrency,
bytes calldata payload
) external;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
interface IAsset is IERC20 {
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* _Available since v4.7._
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for memory arrays with automatic capacity resizing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DynamicArrayLib.sol)
library DynamicArrayLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Type to represent a dynamic array in memory.
/// You can directly assign to `data`, and the `p` function will
/// take care of the memory allocation.
struct DynamicArray {
uint256[] data;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the element is not found in the array.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UINT256 ARRAY OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Low level minimalist uint256 array operations.
// If you don't need syntax sugar, it's recommended to use these.
// Some of these functions returns the same array for function chaining.
// e.g. `array.set(0, 1).set(1, 2)`.
/// @dev Returns a uint256 array with `n` elements. The elements are not zeroized.
function malloc(uint256 n) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := or(sub(0, shr(32, n)), mload(0x40))
mstore(result, n)
mstore(0x40, add(add(result, 0x20), shl(5, n)))
}
}
/// @dev Zeroizes all the elements of `a`.
function zeroize(uint256[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
codecopy(add(result, 0x20), codesize(), shl(5, mload(result)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function get(uint256[] memory a, uint256 i) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function getUint256(uint256[] memory a, uint256 i) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function getAddress(uint256[] memory a, uint256 i) internal pure returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function getBool(uint256[] memory a, uint256 i) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function getBytes32(uint256[] memory a, uint256 i) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(uint256[] memory a, uint256 i, uint256 data)
internal
pure
returns (uint256[] memory result)
{
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(result, 0x20), shl(5, i)), data)
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(uint256[] memory a, uint256 i, address data)
internal
pure
returns (uint256[] memory result)
{
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(result, 0x20), shl(5, i)), shr(96, shl(96, data)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(uint256[] memory a, uint256 i, bool data)
internal
pure
returns (uint256[] memory result)
{
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(result, 0x20), shl(5, i)), iszero(iszero(data)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(uint256[] memory a, uint256 i, bytes32 data)
internal
pure
returns (uint256[] memory result)
{
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(result, 0x20), shl(5, i)), data)
}
}
/// @dev Casts `a` to `address[]`.
function asAddressArray(uint256[] memory a) internal pure returns (address[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `bool[]`.
function asBoolArray(uint256[] memory a) internal pure returns (bool[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `bytes32[]`.
function asBytes32Array(uint256[] memory a) internal pure returns (bytes32[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `uint256[]`.
function toUint256Array(address[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `uint256[]`.
function toUint256Array(bool[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `uint256[]`.
function toUint256Array(bytes32[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Reduces the size of `a` to `n`.
/// If `n` is greater than the size of `a`, this will be a no-op.
function truncate(uint256[] memory a, uint256 n)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := a
mstore(mul(lt(n, mload(result)), result), n)
}
}
/// @dev Clears the array and attempts to free the memory if possible.
function free(uint256[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
let n := mload(result)
mstore(shl(6, lt(iszero(n), eq(add(shl(5, add(1, n)), result), mload(0x40)))), result)
mstore(result, 0)
}
}
/// @dev Equivalent to `keccak256(abi.encodePacked(a))`.
function hash(uint256[] memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := keccak256(add(a, 0x20), shl(5, mload(a)))
}
}
/// @dev Returns a copy of `a` sliced from `start` to `end` (exclusive).
function slice(uint256[] memory a, uint256 start, uint256 end)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let arrayLen := mload(a)
if iszero(gt(arrayLen, end)) { end := arrayLen }
if iszero(gt(arrayLen, start)) { start := arrayLen }
if lt(start, end) {
result := mload(0x40)
let resultLen := sub(end, start)
mstore(result, resultLen)
a := add(a, shl(5, start))
// Copy the `a` one word at a time, backwards.
let o := shl(5, resultLen)
mstore(0x40, add(add(result, o), 0x20)) // Allocate memory.
for {} 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := sub(o, 0x20)
if iszero(o) { break }
}
}
}
}
/// @dev Returns if `needle` is in `a`.
function contains(uint256[] memory a, uint256 needle) internal pure returns (bool) {
return ~indexOf(a, needle, 0) != 0;
}
/// @dev Returns the first index of `needle`, scanning forward from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(uint256[] memory a, uint256 needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0)
if lt(from, mload(a)) {
let o := add(a, shl(5, from))
let end := add(shl(5, add(1, mload(a))), a)
let c := mload(end) // Cache the word after the array.
for { mstore(end, needle) } 1 {} {
o := add(o, 0x20)
if eq(mload(o), needle) { break }
}
mstore(end, c) // Restore the word after the array.
if iszero(eq(o, end)) { result := shr(5, sub(o, add(0x20, a))) }
}
}
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(uint256[] memory a, uint256 needle) internal pure returns (uint256 result) {
result = indexOf(a, needle, 0);
}
/// @dev Returns the last index of `needle`, scanning backwards from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(uint256[] memory a, uint256 needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0)
let n := mload(a)
if n {
if iszero(lt(from, n)) { from := sub(n, 1) }
let o := add(shl(5, add(2, from)), a)
for { mstore(a, needle) } 1 {} {
o := sub(o, 0x20)
if eq(mload(o), needle) { break }
}
mstore(a, n) // Restore the length.
if iszero(eq(o, a)) { result := shr(5, sub(o, add(0x20, a))) }
}
}
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(uint256[] memory a, uint256 needle)
internal
pure
returns (uint256 result)
{
result = lastIndexOf(a, needle, NOT_FOUND);
}
/// @dev Directly returns `a` without copying.
function directReturn(uint256[] memory a) internal pure {
assembly {
let retStart := sub(a, 0x20)
mstore(retStart, 0x20)
return(retStart, add(0x40, shl(5, mload(a))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DYNAMIC ARRAY OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Some of these functions returns the same array for function chaining.
// e.g. `a.p("1").p("2")`.
/// @dev Shorthand for `a.data.length`.
function length(DynamicArray memory a) internal pure returns (uint256) {
return a.data.length;
}
/// @dev Wraps `a` in a dynamic array struct.
function wrap(uint256[] memory a) internal pure returns (DynamicArray memory result) {
result.data = a;
}
/// @dev Wraps `a` in a dynamic array struct.
function wrap(address[] memory a) internal pure returns (DynamicArray memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(result, a)
}
}
/// @dev Wraps `a` in a dynamic array struct.
function wrap(bool[] memory a) internal pure returns (DynamicArray memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(result, a)
}
}
/// @dev Wraps `a` in a dynamic array struct.
function wrap(bytes32[] memory a) internal pure returns (DynamicArray memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(result, a)
}
}
/// @dev Clears the array without deallocating the memory.
function clear(DynamicArray memory a) internal pure returns (DynamicArray memory result) {
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(mload(result), 0)
}
}
/// @dev Clears the array and attempts to free the memory if possible.
function free(DynamicArray memory a) internal pure returns (DynamicArray memory result) {
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
let arrData := mload(result)
if iszero(eq(arrData, 0x60)) {
let prime := 8188386068317523
let cap := mload(sub(arrData, 0x20))
// Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// If `cap` is non-zero and the memory is contiguous, we can free it.
if lt(iszero(cap), eq(mload(0x40), add(arrData, add(0x20, cap)))) {
mstore(0x40, sub(arrData, 0x20))
}
mstore(result, 0x60)
}
}
}
/// @dev Resizes the array to contain `n` elements. New elements will be zeroized.
function resize(DynamicArray memory a, uint256 n)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
reserve(result, n);
/// @solidity memory-safe-assembly
assembly {
let arrData := mload(result)
let arrLen := mload(arrData)
if iszero(lt(n, arrLen)) {
codecopy(add(arrData, shl(5, add(1, arrLen))), codesize(), shl(5, sub(n, arrLen)))
}
mstore(arrData, n)
}
}
/// @dev Increases the size of `a` to `n`.
/// If `n` is less than the size of `a`, this will be a no-op.
/// This method does not zeroize any newly created elements.
function expand(DynamicArray memory a, uint256 n)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
if (n >= a.data.length) {
reserve(result, n);
/// @solidity memory-safe-assembly
assembly {
mstore(mload(result), n)
}
}
}
/// @dev Reduces the size of `a` to `n`.
/// If `n` is greater than the size of `a`, this will be a no-op.
function truncate(DynamicArray memory a, uint256 n)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(mul(lt(n, mload(mload(result))), mload(result)), n)
}
}
/// @dev Reserves at least `minimum` amount of contiguous memory.
function reserve(DynamicArray memory a, uint256 minimum)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(minimum, 0xffffffff)) { invalid() } // For extra safety.
for { let arrData := mload(a) } 1 {} {
// Some random prime number to multiply `cap`, so that
// we know that the `cap` is for a dynamic array.
// Selected to be larger than any memory pointer realistically.
let prime := 8188386068317523
// Special case for `arrData` pointing to zero pointer.
if eq(arrData, 0x60) {
let newCap := shl(5, add(1, minimum))
let capSlot := mload(0x40)
mstore(capSlot, mul(prime, newCap)) // Store the capacity.
let newArrData := add(0x20, capSlot)
mstore(newArrData, 0) // Store the length.
mstore(0x40, add(newArrData, add(0x20, newCap))) // Allocate memory.
mstore(a, newArrData)
break
}
let w := not(0x1f)
let cap := mload(add(arrData, w)) // `mload(sub(arrData, w))`.
// Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
let newCap := shl(5, minimum)
// If we don't need to grow the memory.
if iszero(and(gt(minimum, mload(arrData)), gt(newCap, cap))) { break }
// If the memory is contiguous, we can simply expand it.
if eq(mload(0x40), add(arrData, add(0x20, cap))) {
mstore(add(arrData, w), mul(prime, newCap)) // Store the capacity.
mstore(0x40, add(arrData, add(0x20, newCap))) // Expand the memory allocation.
break
}
let capSlot := mload(0x40)
let newArrData := add(capSlot, 0x20)
mstore(0x40, add(newArrData, add(0x20, newCap))) // Reallocate the memory.
mstore(a, newArrData) // Store the `newArrData`.
// Copy `arrData` one word at a time, backwards.
for { let o := add(0x20, shl(5, mload(arrData))) } 1 {} {
mstore(add(newArrData, o), mload(add(arrData, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(capSlot, mul(prime, newCap)) // Store the capacity.
mstore(newArrData, mload(arrData)) // Store the length.
break
}
}
}
/// @dev Appends `data` to `a`.
function p(DynamicArray memory a, uint256 data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
let arrData := mload(a)
let newArrLen := add(mload(arrData), 1)
let newArrBytesLen := shl(5, newArrLen)
// Some random prime number to multiply `cap`, so that
// we know that the `cap` is for a dynamic array.
// Selected to be larger than any memory pointer realistically.
let prime := 8188386068317523
let cap := mload(sub(arrData, 0x20))
// Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// Expand / Reallocate memory if required.
// Note that we need to allocate an extra word for the length.
for {} iszero(lt(newArrBytesLen, cap)) {} {
// Approximately more than double the capacity to ensure more than enough space.
let newCap := add(cap, or(cap, newArrBytesLen))
// If the memory is contiguous, we can simply expand it.
if iszero(or(xor(mload(0x40), add(arrData, add(0x20, cap))), eq(arrData, 0x60))) {
mstore(sub(arrData, 0x20), mul(prime, newCap)) // Store the capacity.
mstore(0x40, add(arrData, add(0x20, newCap))) // Expand the memory allocation.
break
}
// Set the `newArrData` to point to the word after `cap`.
let newArrData := add(mload(0x40), 0x20)
mstore(0x40, add(newArrData, add(0x20, newCap))) // Reallocate the memory.
mstore(a, newArrData) // Store the `newArrData`.
let w := not(0x1f)
// Copy `arrData` one word at a time, backwards.
for { let o := newArrBytesLen } 1 {} {
mstore(add(newArrData, o), mload(add(arrData, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(newArrData, w), mul(prime, newCap)) // Store the memory.
arrData := newArrData // Assign `newArrData` to `arrData`.
break
}
mstore(add(arrData, newArrBytesLen), data) // Append `data`.
mstore(arrData, newArrLen) // Store the length.
}
}
/// @dev Appends `data` to `a`.
function p(DynamicArray memory a, address data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = p(a, uint256(uint160(data)));
}
/// @dev Appends `data` to `a`.
function p(DynamicArray memory a, bool data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = p(a, _toUint(data));
}
/// @dev Appends `data` to `a`.
function p(DynamicArray memory a, bytes32 data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = p(a, uint256(data));
}
/// @dev Shorthand for returning an empty array.
function p() internal pure returns (DynamicArray memory result) {}
/// @dev Shorthand for `p(p(), data)`.
function p(uint256 data) internal pure returns (DynamicArray memory result) {
p(result, uint256(data));
}
/// @dev Shorthand for `p(p(), data)`.
function p(address data) internal pure returns (DynamicArray memory result) {
p(result, uint256(uint160(data)));
}
/// @dev Shorthand for `p(p(), data)`.
function p(bool data) internal pure returns (DynamicArray memory result) {
p(result, _toUint(data));
}
/// @dev Shorthand for `p(p(), data)`.
function p(bytes32 data) internal pure returns (DynamicArray memory result) {
p(result, uint256(data));
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function pop(DynamicArray memory a) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function popUint256(DynamicArray memory a) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function popAddress(DynamicArray memory a) internal pure returns (address result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function popBool(DynamicArray memory a) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function popBytes32(DynamicArray memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function get(DynamicArray memory a, uint256 i) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function getUint256(DynamicArray memory a, uint256 i) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function getAddress(DynamicArray memory a, uint256 i) internal pure returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function getBool(DynamicArray memory a, uint256 i) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function getBytes32(DynamicArray memory a, uint256 i) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(DynamicArray memory a, uint256 i, uint256 data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(mload(result), 0x20), shl(5, i)), data)
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(DynamicArray memory a, uint256 i, address data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(mload(result), 0x20), shl(5, i)), shr(96, shl(96, data)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(DynamicArray memory a, uint256 i, bool data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(mload(result), 0x20), shl(5, i)), iszero(iszero(data)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(DynamicArray memory a, uint256 i, bytes32 data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(mload(result), 0x20), shl(5, i)), data)
}
}
/// @dev Returns the underlying array as a `uint256[]`.
function asUint256Array(DynamicArray memory a)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(a)
}
}
/// @dev Returns the underlying array as a `address[]`.
function asAddressArray(DynamicArray memory a)
internal
pure
returns (address[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(a)
}
}
/// @dev Returns the underlying array as a `bool[]`.
function asBoolArray(DynamicArray memory a) internal pure returns (bool[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(a)
}
}
/// @dev Returns the underlying array as a `bytes32[]`.
function asBytes32Array(DynamicArray memory a)
internal
pure
returns (bytes32[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(a)
}
}
/// @dev Returns a copy of `a` sliced from `start` to `end` (exclusive).
function slice(DynamicArray memory a, uint256 start, uint256 end)
internal
pure
returns (DynamicArray memory result)
{
result.data = slice(a.data, start, end);
}
/// @dev Returns a copy of `a` sliced from `start` to the end of the array.
function slice(DynamicArray memory a, uint256 start)
internal
pure
returns (DynamicArray memory result)
{
result.data = slice(a.data, start, type(uint256).max);
}
/// @dev Returns if `needle` is in `a`.
function contains(DynamicArray memory a, uint256 needle) internal pure returns (bool) {
return ~indexOf(a.data, needle, 0) != 0;
}
/// @dev Returns if `needle` is in `a`.
function contains(DynamicArray memory a, address needle) internal pure returns (bool) {
return ~indexOf(a.data, uint160(needle), 0) != 0;
}
/// @dev Returns if `needle` is in `a`.
function contains(DynamicArray memory a, bytes32 needle) internal pure returns (bool) {
return ~indexOf(a.data, uint256(needle), 0) != 0;
}
/// @dev Returns the first index of `needle`, scanning forward from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, uint256 needle, uint256 from)
internal
pure
returns (uint256)
{
return indexOf(a.data, needle, from);
}
/// @dev Returns the first index of `needle`, scanning forward from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, address needle, uint256 from)
internal
pure
returns (uint256)
{
return indexOf(a.data, uint160(needle), from);
}
/// @dev Returns the first index of `needle`, scanning forward from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, bytes32 needle, uint256 from)
internal
pure
returns (uint256)
{
return indexOf(a.data, uint256(needle), from);
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, uint256 needle) internal pure returns (uint256) {
return indexOf(a.data, needle, 0);
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, address needle) internal pure returns (uint256) {
return indexOf(a.data, uint160(needle), 0);
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, bytes32 needle) internal pure returns (uint256) {
return indexOf(a.data, uint256(needle), 0);
}
/// @dev Returns the last index of `needle`, scanning backwards from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, uint256 needle, uint256 from)
internal
pure
returns (uint256)
{
return lastIndexOf(a.data, needle, from);
}
/// @dev Returns the last index of `needle`, scanning backwards from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, address needle, uint256 from)
internal
pure
returns (uint256)
{
return lastIndexOf(a.data, uint160(needle), from);
}
/// @dev Returns the last index of `needle`, scanning backwards from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, bytes32 needle, uint256 from)
internal
pure
returns (uint256)
{
return lastIndexOf(a.data, uint256(needle), from);
}
/// @dev Returns the last index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, uint256 needle) internal pure returns (uint256) {
return lastIndexOf(a.data, needle, NOT_FOUND);
}
/// @dev Returns the last index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, address needle) internal pure returns (uint256) {
return lastIndexOf(a.data, uint160(needle), NOT_FOUND);
}
/// @dev Returns the last index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, bytes32 needle) internal pure returns (uint256) {
return lastIndexOf(a.data, uint256(needle), NOT_FOUND);
}
/// @dev Equivalent to `keccak256(abi.encodePacked(a.data))`.
function hash(DynamicArray memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := keccak256(add(mload(a), 0x20), shl(5, mload(mload(a))))
}
}
/// @dev Directly returns `a` without copying.
function directReturn(DynamicArray memory a) internal pure {
assembly {
let arrData := mload(a)
let retStart := sub(arrData, 0x20)
mstore(retStart, 0x20)
return(retStart, add(0x40, shl(5, mload(arrData))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Helper for deallocating a automatically allocated array pointer.
function _deallocate(DynamicArray memory result) private pure {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Deallocate, as we have already allocated.
}
}
/// @dev Casts the bool into a uint256.
function _toUint(bool b) private pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IBaseCollateralVault} from "./IBaseCollateralVault.sol";
import {IInfraredWrapper} from "./IInfraredWrapper.sol";
import {IPositionManager} from "../IPositionManager.sol";
import {ICore} from "../ICore.sol";
import {IInfraredVault} from "../../utils/integrations/IInfraredVault.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";
interface IInfraredCollateralVault is IBaseCollateralVault {
struct InfraredCollVaultStorage {
uint16 minPerformanceFee;
uint16 maxPerformanceFee;
uint16 performanceFee; // over yield, in basis points
address iRedToken;
/// @dev We currently don't know the infraredVault implementation, but if it were to be possible for them to remove tokens from the rewardTokens
/// There would be no need to remove it from here since the amounts should continue being accounted for in the virtual balance
EnumerableSet.AddressSet rewardedTokens;
IInfraredVault _infraredVault;
address ibgtVault;
address ibgt;
IInfraredWrapper infraredWrapper;
uint96 lastUpdate;
mapping(address tokenIn => uint) threshold;
}
struct InfraredInitParams {
BaseInitParams _baseParams;
uint16 _minPerformanceFee;
uint16 _maxPerformanceFee;
uint16 _performanceFee; // over yield, in basis points
address _iRedToken;
IInfraredVault _infraredVault;
address _ibgtVault;
address _infraredWrapper;
}
struct RebalanceParams {
address sentCurrency;
uint sentAmount;
address swapper;
bytes payload;
}
function rebalance(RebalanceParams calldata p) external;
function pullRewards() external;
function setUnlockRatePerSecond(address token, uint64 _unlockRatePerSecond) external;
function internalizeDonations(address[] memory tokens, uint128[] memory amounts) external;
function setPairThreshold(address tokenIn, uint thresholdInBP) external;
function setPerformanceFee(uint16 _performanceFee) external;
function setWithdrawFee(uint16 _withdrawFee) external;
function getBalance(address token) external view returns (uint);
function getBalanceOfWithFutureEmissions(address token) external view returns (uint);
function getFullProfitUnlockTimestamp(address token) external view returns (uint);
function unlockRatePerSecond(address token) external view returns (uint);
function getLockedEmissions(address token) external view returns (uint);
function getPerformanceFee() external view returns (uint16);
function rewardedTokens() external view returns (address[] memory);
function iRedToken() external view returns (address);
function infraredVault() external view returns (IInfraredVault);
function ibgt() external view returns (address);
function ibgtVault() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface IMetaCore {
// ---------------------------------
// Structures
// ---------------------------------
struct FeeInfo {
bool existsForDebtToken;
uint16 debtTokenFee;
}
struct RebalancerFeeInfo {
bool exists;
uint16 entryFee;
uint16 exitFee;
}
// ---------------------------------
// Public constants
// ---------------------------------
function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);
function DEFAULT_FLASH_LOAN_FEE() external view returns (uint16);
// ---------------------------------
// Public state variables
// ---------------------------------
function debtToken() external view returns (address);
function lspEntryFee() external view returns (uint16);
function lspExitFee() external view returns (uint16);
function interestProtocolShare() external view returns (uint16);
/// @dev Default interest receiver for all PositionManagers, unless overriden in the respective PM
function defaultInterestReceiver() external view returns (address);
function feeReceiver() external view returns (address);
function priceFeed() external view returns (address);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function ownershipTransferDeadline() external view returns (uint256);
function guardian() external view returns (address);
function paused() external view returns (bool);
function lspBootstrapPeriod() external view returns (uint64);
// ---------------------------------
// External functions
// ---------------------------------
function setFeeReceiver(address _feeReceiver) external;
function setPriceFeed(address _priceFeed) external;
function setGuardian(address _guardian) external;
/**
* @notice Global pause/unpause
* Pausing halts new deposits/borrowing across the protocol
*/
function setPaused(bool _paused) external;
/**
* @notice Extend or change the LSP bootstrap period,
* after which certain protocol mechanics change
*/
function setLspBootstrapPeriod(uint64 _bootstrapPeriod) external;
/**
* @notice Set a custom flash-loan fee for a given periphery contract
* @param _periphery Target contract that will get this custom fee
* @param _debtTokenFee Fee in basis points (bp)
* @param _existsForDebtToken Whether this custom fee is used when the caller = `debtToken`
*/
function setPeripheryFlashLoanFee(address _periphery, uint16 _debtTokenFee, bool _existsForDebtToken) external;
/**
* @notice Begin the ownership transfer process
* @param newOwner The address proposed to be the new owner
*/
function commitTransferOwnership(address newOwner) external;
/**
* @notice Finish the ownership transfer, after the mandatory delay
*/
function acceptTransferOwnership() external;
/**
* @notice Revoke a pending ownership transfer
*/
function revokeTransferOwnership() external;
/**
* @notice Look up a custom flash-loan fee for a specific periphery contract
* @param peripheryContract The contract that might have a custom fee
* @return The flash-loan fee in basis points
*/
function getPeripheryFlashLoanFee(address peripheryContract) external view returns (uint16);
/**
* @notice Set / override entry & exit fees for a special rebalancer contract
*/
function setRebalancerFee(address _rebalancer, uint16 _entryFee, uint16 _exitFee) external;
/**
* @notice Set the LSP entry fee globally
* @param _fee Fee in basis points
*/
function setEntryFee(uint16 _fee) external;
/**
* @notice Set the LSP exit fee globally
* @param _fee Fee in basis points
*/
function setExitFee(uint16 _fee) external;
/**
* @notice Set the interest protocol share globally to all PositionManagers
* @param _interestProtocolShare Share in basis points
*/
function setInterestProtocolShare(uint16 _interestProtocolShare) external;
/**
* @notice Look up the LSP entry fee for a rebalancer
* @param rebalancer Possibly has a special fee
* @return The entry fee in basis points
*/
function getLspEntryFee(address rebalancer) external view returns (uint16);
/**
* @notice Look up the LSP exit fee for a rebalancer
* @param rebalancer Possibly has a special fee
* @return The exit fee in basis points
*/
function getLspExitFee(address rebalancer) external view returns (uint16);
// ---------------------------------
// Events
// ---------------------------------
event NewOwnerCommitted(address indexed owner, address indexed pendingOwner, uint256 deadline);
event NewOwnerAccepted(address indexed oldOwner, address indexed newOwner);
event NewOwnerRevoked(address indexed owner, address indexed revokedOwner);
event FeeReceiverSet(address indexed feeReceiver);
event PriceFeedSet(address indexed priceFeed);
event GuardianSet(address indexed guardian);
event PeripheryFlashLoanFee(address indexed periphery, uint16 debtTokenFee);
event LSPBootstrapPeriodSet(uint64 bootstrapPeriod);
event RebalancerFees(address indexed rebalancer, uint16 entryFee, uint16 exitFee);
event EntryFeeSet(uint16 fee);
event ExitFeeSet(uint16 fee);
event InterestProtocolShareSet(uint16 interestProtocolShare);
event DefaultInterestReceiverSet(address indexed defaultInterestReceiver);
event Paused();
event Unpaused();
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC3156FlashBorrower.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC3156 FlashBorrower, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* _Available since v4.1._
*/
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "IERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC4626, IERC20} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {IPositionManager} from "../IPositionManager.sol";
import {IMetaCore} from "../IMetaCore.sol";
import {IPriceFeed} from "../IPriceFeed.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";
interface IBaseCollateralVault is IERC4626, IERC1822Proxiable {
struct BaseInitParams {
uint16 _minWithdrawFee;
uint16 _maxWithdrawFee;
uint16 _withdrawFee;
IMetaCore _metaCore;
// ERC4626
IERC20 _asset;
// ERC20
string _sharesName;
string _sharesSymbol;
}
struct BaseCollVaultStorage {
uint16 minWithdrawFee;
uint16 maxWithdrawFee;
uint16 withdrawFee; // over rewarded tokens, in basis points
uint8 assetDecimals;
IMetaCore _metaCore;
// Second mapping of this struct is usless, but it's for retrocompatibility with InfraredCollateralVault
EmissionsLib.BalanceData balanceData;
}
function totalAssets() external view returns (uint);
function fetchPrice() external view returns (uint);
function getPrice(address token) external view returns (uint);
function receiveDonations(address[] memory tokens, uint[] memory amounts, address receiver) external;
function setWithdrawFee(uint16 _withdrawFee) external;
function getBalance(address token) external view returns (uint);
function getWithdrawFee() external view returns (uint16);
function getMetaCore() external view returns (IMetaCore);
function getPriceFeed() external view returns (IPriceFeed);
function assetDecimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
interface IInfraredWrapper is IERC20 {
function metaCore() external view returns (address);
function infraredCollVault() external view returns (address);
function decimals() external view returns (uint8);
function depositFor(address account, uint256 amount) external returns (bool);
function withdrawTo(address account, uint256 amount) external returns (bool);
function recover(address account) external returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC3156FlashBorrower} from "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IFactory} from "./IFactory.sol";
interface IPositionManager {
event BaseRateUpdated(uint256 _baseRate);
event CollateralSent(address _to, uint256 _amount);
event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);
event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);
event Redemption(
address indexed _redeemer,
uint256 _attemptedDebtAmount,
uint256 _actualDebtAmount,
uint256 _collateralSent,
uint256 _collateralFee
);
event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);
event TotalStakesUpdated(uint256 _newTotalStakes);
event PositionIndexUpdated(address _borrower, uint256 _newIndex);
event PositionSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);
event PositionUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 _stake, uint8 _operation);
function addCollateralSurplus(address borrower, uint256 collSurplus) external;
function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt);
function claimCollateral(address borrower, address _receiver) external;
function closePosition(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external;
function closePositionByLiquidation(address _borrower) external;
function setCollVaultRouter(address _collVaultRouter) external;
function collectInterests() external;
function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256);
function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external;
function fetchPrice() external view returns (uint256);
function finalizeLiquidation(
address _liquidator,
uint256 _debt,
uint256 _coll,
uint256 _collSurplus,
uint256 _debtGasComp,
uint256 _collGasComp
) external;
function getEntireSystemBalances() external view returns (uint256, uint256, uint256);
function movePendingPositionRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external;
function openPosition(
address _borrower,
uint256 _collateralAmount,
uint256 _compositeDebt,
uint256 NICR,
address _upperHint,
address _lowerHint
) external returns (uint256 stake, uint256 arrayIndex);
function redeemCollateral(
uint256 _debtAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint256 _partialRedemptionHintNICR,
uint256 _maxIterations,
uint256 _maxFeePercentage
) external;
function setAddresses(address _priceFeedAddress, address _sortedPositionsAddress, address _collateralToken) external;
function setParameters(
IFactory.DeploymentParams calldata _params
) external;
function setPaused(bool _paused) external;
function setPriceFeed(address _priceFeedAddress) external;
function startSunset() external;
function updateBalances() external;
function updatePositionFromAdjustment(
bool _isDebtIncrease,
uint256 _debtChange,
uint256 _netDebtChange,
bool _isCollIncrease,
uint256 _collChange,
address _upperHint,
address _lowerHint,
address _borrower,
address _receiver
) external returns (uint256, uint256, uint256);
function DEBT_GAS_COMPENSATION() external view returns (uint256);
function DECIMAL_PRECISION() external view returns (uint256);
function L_collateral() external view returns (uint256);
function L_debt() external view returns (uint256);
function MCR() external view returns (uint256);
function PERCENT_DIVISOR() external view returns (uint256);
function CORE() external view returns (address);
function SUNSETTING_INTEREST_RATE() external view returns (uint256);
function Positions(
address
)
external
view
returns (
uint256 debt,
uint256 coll,
uint256 stake,
uint8 status,
uint128 arrayIndex,
uint256 activeInterestIndex
);
function activeInterestIndex() external view returns (uint256);
function baseRate() external view returns (uint256);
function borrowerOperations() external view returns (address);
function borrowingFeeFloor() external view returns (uint256);
function collateralToken() external view returns (address);
function debtToken() external view returns (address);
function collVaultRouter() external view returns (address);
function defaultedCollateral() external view returns (uint256);
function defaultedDebt() external view returns (uint256);
function getBorrowingFee(uint256 _debt) external view returns (uint256);
function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256);
function getBorrowingRate() external view returns (uint256);
function getBorrowingRateWithDecay() external view returns (uint256);
function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);
function getEntireDebtAndColl(
address _borrower
) external view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward);
function getEntireSystemColl() external view returns (uint256);
function getEntireSystemDebt() external view returns (uint256);
function getNominalICR(address _borrower) external view returns (uint256);
function getPendingCollAndDebtRewards(address _borrower) external view returns (uint256, uint256);
function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256);
function getRedemptionRate() external view returns (uint256);
function getRedemptionRateWithDecay() external view returns (uint256);
function getTotalActiveCollateral() external view returns (uint256);
function getTotalActiveDebt() external view returns (uint256);
function getPositionCollAndDebt(address _borrower) external view returns (uint256 coll, uint256 debt);
function getPositionFromPositionOwnersArray(uint256 _index) external view returns (address);
function getPositionOwnersCount() external view returns (uint256);
function getPositionStake(address _borrower) external view returns (uint256);
function getPositionStatus(address _borrower) external view returns (uint256);
function guardian() external view returns (address);
function hasPendingRewards(address _borrower) external view returns (bool);
function interestPayable() external view returns (uint256);
function interestRate() external view returns (uint256);
function lastActiveIndexUpdate() external view returns (uint256);
function lastCollateralError_Redistribution() external view returns (uint256);
function lastDebtError_Redistribution() external view returns (uint256);
function lastFeeOperationTime() external view returns (uint256);
function liquidationManager() external view returns (address);
function maxBorrowingFee() external view returns (uint256);
function maxRedemptionFee() external view returns (uint256);
function maxSystemDebt() external view returns (uint256);
function minuteDecayFactor() external view returns (uint256);
function owner() external view returns (address);
function paused() external view returns (bool);
function priceFeed() external view returns (address);
function redemptionFeeFloor() external view returns (uint256);
function rewardSnapshots(address) external view returns (uint256 collateral, uint256 debt);
function sortedPositions() external view returns (address);
function sunsetting() external view returns (bool);
function surplusBalances(address) external view returns (uint256);
function systemDeploymentTime() external view returns (uint256);
function totalCollateralSnapshot() external view returns (uint256);
function totalStakes() external view returns (uint256);
function totalStakesSnapshot() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface IInfraredVault {
function stakingToken() external view returns (address);
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function getRewardForUser(address account) external;
function rewardTokens(uint) external view returns (address);
function getAllRewardTokens() external view returns (address[] memory);
function earned(address account, address _rewardsToken) external view returns (uint256);
function registerVault(address stakingToken) external returns (address);
function balanceOf(address account) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface IFactory {
// commented values are suggested default parameters
struct DeploymentParams {
uint256 minuteDecayFactor; // 999037758833783000 (half life of 12 hours)
uint256 redemptionFeeFloor; // 1e18 / 1000 * 5 (0.5%)
uint256 maxRedemptionFee; // 1e18 (100%)
uint256 borrowingFeeFloor; // 1e18 / 1000 * 5 (0.5%)
uint256 maxBorrowingFee; // 1e18 / 100 * 5 (5%)
uint256 interestRateInBps; // 100 (1%)
uint256 maxDebt;
uint256 MCR; // 12 * 1e17 (120%)
address collVaultRouter; // set to address(0) if PositionManager coll is not CollateralVault
}
event NewDeployment(address collateral, address priceFeed, address positionManager, address sortedPositions);
function deployNewInstance(
address collateral,
address priceFeed,
address customPositionManagerImpl,
address customSortedPositionsImpl,
DeploymentParams calldata params,
uint64 unlockRatePerSecond,
bool forceThroughLspBalanceCheck
) external;
function setImplementations(address _positionManagerImpl, address _sortedPositionsImpl) external;
function CORE() external view returns (address);
function borrowerOperations() external view returns (address);
function debtToken() external view returns (address);
function guardian() external view returns (address);
function liquidationManager() external view returns (address);
function owner() external view returns (address);
function sortedPositionsImpl() external view returns (address);
function liquidStabilityPool() external view returns (address);
function positionManagerCount() external view returns (uint256);
function positionManagerImpl() external view returns (address);
function positionManagers(uint256) external view returns (address);
}{
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin-upgradeable/contracts/=lib/openzeppelin-contracts-upgradeable/contracts/",
"solady/=lib/solady/src/",
"@solmate/=lib/solmate/src/",
"@chimera/=lib/chimera/src/",
"forge-std/=lib/forge-std/src/",
"@uniswap/v3-core/=lib/v3-core/",
"@uniswap/v3-periphery/=lib/v3-periphery/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"chimera/=lib/chimera/src/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"rewards/=lib/rewards/",
"solmate/=lib/solmate/src/",
"uniswap/=lib/uniswap/",
"v3-core/=lib/v3-core/contracts/",
"v3-periphery/=lib/v3-periphery/contracts/"
],
"optimizer": {
"enabled": true,
"runs": 1
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AddressZero","type":"error"},{"inputs":[],"name":"AmountCannotBeZero","type":"error"},{"inputs":[],"name":"BalanceRemaining","type":"error"},{"inputs":[],"name":"BelowThreshold","type":"error"},{"inputs":[],"name":"BootstrapPeriod","type":"error"},{"inputs":[],"name":"CallerNotFactory","type":"error"},{"inputs":[],"name":"CallerNotLM","type":"error"},{"inputs":[],"name":"CollateralIsSunsetting","type":"error"},{"inputs":[],"name":"CollateralMustBeSunset","type":"error"},{"inputs":[],"name":"DuplicateToken","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxDeposit","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxMint","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxRedeem","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxWithdraw","type":"error"},{"inputs":[],"name":"EmissionRateExceedsMax","type":"error"},{"inputs":[],"name":"ExistingCollateral","type":"error"},{"inputs":[],"name":"FactoryAlreadyRegistered","type":"error"},{"inputs":[],"name":"FactoryNotRegistered","type":"error"},{"inputs":[],"name":"InvalidArrayLength","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidThreshold","type":"error"},{"inputs":[],"name":"InvalidToken","type":"error"},{"inputs":[],"name":"LMAlreadyRegistered","type":"error"},{"inputs":[],"name":"LMNotRegistered","type":"error"},{"inputs":[],"name":"LastTokenMustBeDebtToken","type":"error"},{"inputs":[],"name":"NoPriceFeed","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"OnlyOwner","type":"error"},{"inputs":[],"name":"Paused","type":"error"},{"inputs":[],"name":"SameTokens","type":"error"},{"inputs":[],"name":"TokenCannotBeDebtToken","type":"error"},{"inputs":[],"name":"TokenCannotBeExtraAsset","type":"error"},{"inputs":[],"name":"TokenIsVesting","type":"error"},{"inputs":[],"name":"TokenMustBeExtraAsset","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"inputs":[],"name":"WithdrawingLockedEmissions","type":"error"},{"inputs":[],"name":"ZeroTotalSupply","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"address[]","name":"tokens","type":"address[]"},{"indexed":false,"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"AssetsWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldCollateral","type":"address"},{"indexed":false,"internalType":"address","name":"newCollateral","type":"address"}],"name":"CollateralOverwritten","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"EmissionsAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"EmissionsSub","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"}],"name":"ExtraAssetAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"}],"name":"ExtraAssetRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint64","name":"unlockRatePerSecond","type":"uint64"}],"name":"NewUnlockRatePerSecond","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"collateral","type":"address"},{"indexed":false,"internalType":"uint256","name":"debtToOffset","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"collToAdd","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"collSurplusAmount","type":"uint256"}],"name":"Offset","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"factoryRemoved","type":"address"},{"indexed":true,"internalType":"address","name":"LMremoved","type":"address"}],"name":"ProtocolBlacklisted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"factory","type":"address"},{"indexed":true,"internalType":"address","name":"liquidationManager","type":"address"}],"name":"ProtocolRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sentCurrency","type":"address"},{"indexed":true,"internalType":"address","name":"receivedCurrency","type":"address"},{"indexed":false,"internalType":"uint256","name":"sentAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"receivedAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sentValue","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"receivedValue","type":"uint256"}],"name":"Rebalance","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"SUNSET_DURATION","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint64","name":"_unlockRatePerSecond","type":"uint64"}],"name":"addNewExtraAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_collateral","type":"address"},{"internalType":"uint64","name":"_unlockRatePerSecond","type":"uint64"},{"internalType":"bool","name":"forceThroughBalanceCheck","type":"bool"}],"name":"enableCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"slots","type":"bytes32[]"}],"name":"extSloads","outputs":[{"internalType":"bytes32[]","name":"res","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCollateralTokens","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getLockedEmissions","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getPrice","outputs":[{"internalType":"uint256","name":"scaledPriceInUsdWad","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalDebtTokenDeposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"_asset","type":"address"},{"internalType":"string","name":"_sharesName","type":"string"},{"internalType":"string","name":"_sharesSymbol","type":"string"},{"internalType":"contract IMetaCore","name":"_metaCore","type":"address"},{"internalType":"address","name":"_liquidationManager","type":"address"},{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_feeReceiver","type":"address"}],"internalType":"struct ILiquidStabilityPool.InitParams","name":"params","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"int256","name":"amount","type":"int256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"linearVestingExtraAssets","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"collateral","type":"address"},{"internalType":"uint256","name":"_debtToOffset","type":"uint256"},{"internalType":"uint256","name":"_collToAdd","type":"uint256"}],"name":"offset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"netShares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"sentCurrency","type":"address"},{"internalType":"uint256","name":"sentAmount","type":"uint256"},{"internalType":"address","name":"receivedCurrency","type":"address"},{"internalType":"address","name":"swapper","type":"address"},{"internalType":"bytes","name":"payload","type":"bytes"}],"internalType":"struct ILiquidStabilityPool.RebalanceParams","name":"p","type":"tuple"}],"name":"rebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address[]","name":"preferredUnderlyingTokens","type":"address[]"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"removeExtraAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"thresholdInBP","type":"uint256"}],"name":"setPairThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"redeemers","type":"address[]"},{"internalType":"bool[]","name":"enables","type":"bool[]"}],"name":"setPrivilegedDebtRedeemers","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint64","name":"_unlockRatePerSecond","type":"uint64"}],"name":"setUnlockRatePerSecond","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"collateral","type":"address"}],"name":"startCollateralSunset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"amountInDebtToken","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_liquidationManager","type":"address"},{"internalType":"address","name":"_factory","type":"address"},{"internalType":"bool","name":"_register","type":"bool"}],"name":"updateProtocol","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address[]","name":"preferredUnderlyingTokens","type":"address[]"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
60a060405230608052348015610013575f80fd5b5061001c610021565b6100d3565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff16156100715760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146100d05780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b608051615bf66100f95f395f81816133a0015281816133c901526134ff0152615bf65ff3fe608060405260043610610222575f3560e01c806301e1d1141461022657806306fdde031461024d57806307a2d13a1461026e578063095ea7b31461028d5780630a28a477146102bc5780630b983a74146102db5780630d9a6b35146102fc57806315450da01461031057806318160ddd1461032f57806319f27b3b1461034357806323b872dd14610362578063313ce5671461038157806331e95162146103a757806338d52e0f146103c6578063402d267d146103e7578063403dd3bc1461040757806341976e09146104265780634cdad506146104455780634f1ef2861461046457806352d1902d14610477578063602ecae51461048b5780636cd611be146104aa5780636e553f65146104c957806370a08231146104e85780637784c685146105075780637b8b8b74146105335780637facd79b1461055257806394bf804d1461057157806395d89b4114610590578063a7528a03146105a4578063a9059cbb146105c7578063ad3cb1cc146105e6578063b3d7f6b914610616578063b460af9414610635578063b58eb63f14610654578063ba08765214610675578063badd8b2d14610694578063c5e6a767146106b3578063c63d75b6146103e7578063c6e6f592146106d2578063ce96cb77146106f1578063d905777e14610710578063dd62ed3e1461072f578063ddda679b1461074e578063e66667331461076d578063ef8b30f71461078c578063fcb99905146107ab578063fd694144146107ca575b5f80fd5b348015610231575f80fd5b5061023a6107e9565b6040519081526020015b60405180910390f35b348015610258575f80fd5b506102616109ab565b6040516102449190614f87565b348015610279575f80fd5b5061023a610288366004614fbc565b610a49565b348015610298575f80fd5b506102ac6102a7366004614fe7565b610a5a565b6040519015158152602001610244565b3480156102c7575f80fd5b5061023a6102d6366004614fbc565b610a71565b3480156102e6575f80fd5b506102fa6102f5366004615025565b610aab565b005b348015610307575f80fd5b5061023a610ad1565b34801561031b575f80fd5b506102fa61032a3660046150a3565b610b0b565b34801561033a575f80fd5b5061023a610bd2565b34801561034e575f80fd5b506102fa61035d36600461510d565b610be6565b34801561036d575f80fd5b506102ac61037c366004615128565b610d1a565b34801561038c575f80fd5b50610395610d3f565b60405160ff9091168152602001610244565b3480156103b2575f80fd5b5061023a6103c1366004615166565b610d68565b3480156103d1575f80fd5b506103da610e5f565b60405161024491906151d4565b3480156103f2575f80fd5b5061023a61040136600461510d565b505f1990565b348015610412575f80fd5b5061023a61042136600461510d565b610e79565b348015610431575f80fd5b5061023a61044036600461510d565b610ef3565b348015610450575f80fd5b5061023a61045f366004614fbc565b610fd5565b6102fa6104723660046151fc565b610ff8565b348015610482575f80fd5b5061023a611017565b348015610496575f80fd5b506102fa6104a53660046152cc565b611032565b3480156104b5575f80fd5b506102fa6104c436600461510d565b6112bc565b3480156104d4575f80fd5b5061023a6104e3366004615314565b6113f2565b3480156104f3575f80fd5b5061023a61050236600461510d565b6114ba565b348015610512575f80fd5b50610526610521366004615337565b6114e3565b6040516102449190615375565b34801561053e575f80fd5b506102fa61054d3660046153b7565b611572565b34801561055d575f80fd5b506102fa61056c3660046153e4565b6116b7565b34801561057c575f80fd5b5061023a61058b366004615314565b611d44565b34801561059b575f80fd5b50610261611e24565b3480156105af575f80fd5b506105ba62093a8081565b604051610244919061541a565b3480156105d2575f80fd5b506102ac6105e1366004614fe7565b611e40565b3480156105f1575f80fd5b50610261604051806040016040528060058152602001640352e302e360dc1b81525081565b348015610621575f80fd5b5061023a610630366004614fbc565b611e4d565b348015610640575f80fd5b5061023a61064f36600461542e565b611e7e565b34801561065f575f80fd5b50610668611f12565b60405161024491906154a5565b348015610680575f80fd5b5061023a61068f36600461542e565b611f7b565b34801561069f575f80fd5b506102fa6106ae366004615128565b612003565b3480156106be575f80fd5b506102fa6106cd3660046154b7565b61207d565b3480156106dd575f80fd5b5061023a6106ec366004614fbc565b61215c565b3480156106fc575f80fd5b5061023a61070b36600461510d565b612167565b34801561071b575f80fd5b5061023a61072a36600461510d565b612174565b34801561073a575f80fd5b5061023a6107493660046154eb565b61217e565b348015610759575f80fd5b5061023a610768366004615166565b6121b8565b348015610778575f80fd5b506102fa610787366004615517565b612293565b348015610797575f80fd5b5061023a6107a6366004614fbc565b61246e565b3480156107b6575f80fd5b506102fa6107c5366004615025565b612489565b3480156107d5575f80fd5b506102fa6107e4366004615549565b6126ae565b5f806107f361293d565b90505f806107ff611f12565b90505f61080d610440610e5f565b82519091505f61081f60028701612961565b90505f600987018161082f610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f205490505f5b83811015610922575f86828151811061086e5761086e61557f565b602002602001015190505f61088f828b60090161296a90919063ffffffff16565b905080156109185761090b6108a383610ef3565b836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108df573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109039190615593565b8391906129f6565b610915908a6155c7565b98505b5050600101610853565b505f5b82811015610976575f61093b60028a0183612a16565b90505f61094b60098b018361296a565b9050801561096c5761095f6108a383610ef3565b610969908a6155c7565b98505b5050600101610925565b50808461098b670de0b6b3a7640000896155da565b6109959190615605565b61099f91906155c7565b97505050505050505090565b60605f6109b6612a21565b90508060030180546109c790615624565b80601f01602080910402602001604051908101604052809291908181526020018280546109f390615624565b8015610a3e5780601f10610a1557610100808354040283529160200191610a3e565b820191905f5260205f20905b815481529060010190602001808311610a2157829003601f168201915b505050505091505090565b5f610a54825f612a45565b92915050565b5f33610a67818585612a82565b5060019392505050565b5f80610a7c83612a8f565b90505f610aa3612710610a8d612a9b565b610a999061271061565c565b8491906001612b1e565b949350505050565b610ab3612b79565b5f610abc61293d565b9050610acc600982018484612c1e565b505050565b5f610ada61293d565b6009015f610ae6610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f2054905090565b610b13612b79565b5f610b1c61293d565b9050838214610b3e57604051634ec4810560e11b815260040160405180910390fd5b5f5b84811015610bca57838382818110610b5a57610b5a61557f565b9050602002016020810190610b6f919061566f565b82600d015f888885818110610b8657610b8661557f565b9050602002016020810190610b9b919061510d565b6001600160a01b0316815260208101919091526040015f20805460ff1916911515919091179055600101610b40565b505050505050565b5f80610bdc612a21565b6002015492915050565b610bee612b79565b5f610bf761293d565b6001600160a01b0383165f90815260078201602052604081205491925003610c3257604051630b3cfa8f60e01b815260040160405180910390fd5b6040805180820182526001600160a01b0384165f9081526007840160205291909120548190610c639060019061565c565b6001600160801b03168152602001610c7e62093a80426155c7565b6001600160801b0316905260048201805460068401915f9162010000900461ffff16906002610cac8361568a565b825461ffff9182166101009390930a92830292820219169190911790915516815260208082019290925260409081015f9081208451948401516001600160801b03908116600160801b029516949094179093556001600160a01b039094168252600790920190915290812055565b5f33610d27858285612ccc565b610d32858585612d16565b60019150505b9392505050565b5f80610d49612d73565b90505f8154610d629190600160a01b900460ff166156aa565b91505090565b5f610d71612d97565b5f610d7a61293d565b90505f610d8684612174565b905080881115610db857838882604051632e52afbb60e21b8152600401610daf939291906156c3565b60405180910390fd5b610dc188610fd5565b9250610dcf82895f87612e3a565b5050610e1082848989808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152508b9250612eeb915050565b836001600160a01b0316856001600160a01b0316336001600160a01b03165f80516020615b3a833981519152868c604051610e4c9291906156e4565b60405180910390a4505095945050505050565b5f80610e69612d73565b546001600160a01b031692915050565b5f80610e8361293d565b6001600160a01b0384165f908152600a90910160209081526040808320815160608101835290546001600160801b03811682526001600160401b03600160801b8204811694830194909452600160c01b9004909216908201529150610ee7826132cd565b9050610aa382826132fe565b5f80610efd61293d565b5460408051633a0df78d60e11b815290516001600160a01b039092169163741bef1a916004808201926020929091908290030181865afa158015610f43573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f6791906156f2565b604051635670bcc760e11b81529091506001600160a01b0382169063ace1798e90610f969086906004016151d4565b602060405180830381865afa158015610fb1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d38919061570d565b5f80610fe9610fe2612a9b565b8490613385565b9050610d38610288828561565c565b611000613395565b61100982613439565b6110138282613441565b5050565b5f6110206134f4565b505f80516020615b5a83398151915290565b5f61103b61293d565b9050611045610e5f565b6001600160a01b0316846001600160a01b0316036110765760405163d3c4f33360e01b815260040160405180910390fd5b335f908152600b8201602052604090205460ff166110a75760405163a84178ab60e01b815260040160405180910390fd5b6110b4600282018561353d565b156110d257604051631cf57a9f60e11b815260040160405180910390fd5b60058101545f6110e6600984018787612c1e565b5f5b8281101561113957866001600160a01b031684600501828154811061110f5761110f61557f565b5f918252602090912001546001600160a01b0316036111315760019150611139565b6001016110e8565b50806112695760408051808201909152600484015461ffff808216808452620100009092041660208301819052111561121e57805161ffff165f9081526006850160209081526040918290208251808401909352546001600160801b038082168452600160801b9091041690820181905242111561121c5760048501805460068701915f9161ffff1690826111cd8361568a565b82546101009290920a61ffff81810219909316918316021790915516815260208101919091526040015f9081205580516112129089906001600160801b031688613551565b5050505050505050565b505b506005830180546001810182555f828152602080822090920180546001600160a01b0319166001600160a01b038b169081179091559254928152600786019091526040902055610bca565b6001600160a01b0386165f9081526007840160205260409020541580156112a357604051630b3cfa8f60e01b815260040160405180910390fd5b6040516360f7af0b60e11b815260040160405180910390fd5b6112c4612b79565b5f6112cd61293d565b6001600160a01b0383165f90815260098201602052604090205490915015611308576040516305ec751560e51b815260040160405180910390fd5b6001600160a01b0382165f908152600a82016020908152604091829020825160608101845290546001600160801b03811682526001600160401b03600160801b8204811693830193909352600160c01b900490911691810191909152429061136f906132cd565b1061138d5760405163fda6d69360e01b815260040160405180910390fd5b61139a60028201836136a6565b6113b75760405163081fcdbf60e21b815260040160405180910390fd5b7ffc9138846a97b86614d19b78419b88e555c50bbd80b03feffd6264cd43064380826040516113e691906151d4565b60405180910390a15050565b5f806113fc61293d565b805460408051635c975abb60e01b815290519293506001600160a01b0390911691635c975abb916004808201926020929091908290030181865afa158015611446573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061146a9190615724565b15611488576040516313d0ff5960e31b815260040160405180910390fd5b5f80611493866136ba565b90925090506114a2818361565c565b93506114b183858888856136e0565b50505092915050565b5f806114c4612a21565b6001600160a01b039093165f9081526020939093525050604090205490565b606081806001600160401b038111156114fe576114fe6151e8565b604051908082528060200260200182016040528015611527578160200160208202803683370190505b5091505f5b8181101561156a575f8585836115418161573f565b94508181106115525761155261557f565b9050602002013590508054602083028501525061152c565b505092915050565b61157a612b79565b5f61158361293d565b90506001600160a01b03841615806115a257506001600160a01b038316155b156115c057604051639fabe1c160e01b815260040160405180910390fd5b81156115d6576115d1818585613766565b6116b1565b6001600160a01b0383165f908152600b8201602052604090205460ff16611610576040516335f85eb560e11b815260040160405180910390fd5b6001600160a01b0384165f908152600c8201602052604090205460ff1661164a57604051635819892360e11b815260040160405180910390fd5b6001600160a01b038084165f818152600b840160209081526040808320805460ff19908116909155948916808452600c8701909252808320805490951690945592517f88ecee496061ddc38d88503f7cf6a1f4f6ade60ee216c946c5a0e8de6049595c9190a35b50505050565b6116bf612b79565b5f6116c861293d565b90506116da606083016040840161510d565b6001600160a01b03166116f0602084018461510d565b6001600160a01b03160361171757604051630d11785f60e21b815260040160405180910390fd5b5f611728610440602085018561510d565b90505f61173e610440606086016040870161510d565b90505f61174e602086018661510d565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611789573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117ad9190615593565b90505f6117c0606087016040880161510d565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117fb573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061181f9190615593565b90505f61182f602088018861510d565b6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161185a91906151d4565b602060405180830381865afa158015611875573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611899919061570d565b90505f6118ac6060890160408a0161510d565b6001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016118d791906151d4565b602060405180830381865afa1580156118f2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611916919061570d565b905061194c61192b60808a0160608b0161510d565b60208a0180359061193c908c61510d565b6001600160a01b0316919061384c565b61195c6080890160608a0161510d565b6001600160a01b0316637f0f41d761197760208b018b61510d565b60208b013561198c60608d0160408e0161510d565b61199960808e018e615757565b6040518663ffffffff1660e01b81526004016119b9959493929190615799565b5f604051808303815f87803b1580156119d0575f80fd5b505af11580156119e2573d5f803e3d5ffd5b505050505f818960400160208101906119fb919061510d565b6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401611a2691906151d4565b602060405180830381865afa158015611a41573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a65919061570d565b611a6f919061565c565b90505f611a7f60208b018b61510d565b6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401611aaa91906151d4565b602060405180830381865afa158015611ac5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ae9919061570d565b611af3908561565c565b9050611b0561042160208c018c61510d565b60098a015f611b1760208e018e61510d565b6001600160a01b03166001600160a01b031681526020019081526020015f2054611b41919061565c565b811115611b6157604051630301465d60e11b815260040160405180910390fd5b5f611b6d8389886129f6565b90505f611b7b838b8a6129f6565b90505f611b8b60208e018e61510d565b8d6040016020810190611b9e919061510d565b604051602001611baf9291906157e9565b6040516020818303038152906040528051906020012090506127108c6008015f8381526020019081526020015f2054612710611beb919061565c565b611bf590846155da565b611bff9190615605565b831015611c1e57604051625713a160e91b815260040160405180910390fd5b838c6009015f015f8f5f016020810190611c38919061510d565b6001600160a01b03166001600160a01b031681526020019081526020015f205f828254611c65919061565c565b92505081905550848c6009015f015f8f6040016020810190611c87919061510d565b6001600160a01b03166001600160a01b031681526020019081526020015f205f828254611cb491906155c7565b90915550611cca905060608e0160408f0161510d565b6001600160a01b0316611ce060208f018f61510d565b6040805187815260208101899052908101859052606081018690526001600160a01b0391909116907fb8c3fd52c06cd7e35d81a3fc31542187d197c9deef253587a27e0214677d0f6b9060800160405180910390a350505050505050505050505050565b5f80611d4e61293d565b805460408051635c975abb60e01b815290519293506001600160a01b0390911691635c975abb916004808201926020929091908290030181865afa158015611d98573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dbc9190615724565b15611dda576040516313d0ff5960e31b815260040160405180910390fd5b611de384611e4d565b91505f84611e0b612710611df56138a2565b611e019061271061565c565b8891906001612b1e565b611e15919061565c565b905061156a82868587856136e0565b60605f611e2f612a21565b90508060040180546109c790615624565b5f33610a67818585612d16565b5f80611e73612710611e5d6138a2565b611e699061271061565c565b8591906001612b1e565b9050610d38816138dc565b5f611e87612d97565b5f611e9061293d565b90505f611e9b610bd2565b90505f611ea785612167565b905080871115611ed057848782604051633fa733bb60e21b8152600401610daf939291906156c3565b611ed987610a71565b93505f80611ee98587868a612e3a565b9092509050611f068289611efd848a61565c565b878b8e8c6138e8565b50505050509392505050565b6060611f1c61293d565b600501805480602002602001604051908101604052809291908181526020018280548015611f7157602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311611f53575b5050505050905090565b5f611f84612d97565b5f611f8d61293d565b90505f611f98610bd2565b90505f611fa485612174565b905080871115611fcd57848782604051632e52afbb60e21b8152600401610daf939291906156c3565b611fd687610fd5565b93505f80611fe6858a868a612e3a565b9092509050611f068289611ffa848d61565c565b878b8b8f6138e8565b61200b612b79565b5f61201461293d565b90506127108211156120395760405163aabd5a0960e01b815260040160405180910390fd5b5f848460405160200161204d9291906157e9565b60408051601f1981840301815291815281516020928301205f908152600890940190915290912091909155505050565b612085612b79565b5f61208e61293d565b9050612098610bd2565b5f036120b7576040516348b5002360e01b815260040160405180910390fd5b6120c4600282018561353d565b6120e15760405163081fcdbf60e21b815260040160405180910390fd5b5f83131561211d57826120ff6001600160a01b03861633308461394a565b6121178561210c8361396b565b6009850191906139d7565b506116b1565b5f6121278461580b565b9050612141856121368361396b565b600985019190613a44565b6121556001600160a01b038616848361384c565b5050505050565b5f610a54825f613ab1565b5f610a5461045f836114ba565b5f610a54826114ba565b5f80612188612a21565b6001600160a01b039485165f90815260019190910160209081526040808320959096168252939093525050205490565b5f6121c1612d97565b5f6121ca61293d565b90505f6121d684612167565b9050808811156121ff57838882604051633fa733bb60e21b8152600401610daf939291906156c3565b61220888610a71565b925061221682845f87612e3a565b505061225782898989808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152508b9250612eeb915050565b836001600160a01b0316856001600160a01b0316336001600160a01b03165f80516020615b3a8339815191528b87604051610e4c9291906156e4565b5f61229c61293d565b335f908152600c8201602052604090205490915060ff166122d0576040516358164d9160e11b815260040160405180910390fd5b5f6122da85610ef3565b90505f6122e8610440610e5f565b90505f61236483836122f8610d3f565b8a6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015612334573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123589190615593565b8a939291906001613ae5565b90505f8186111561237c57612379828761565c565b90505b801561239a5761239a8861238f8361396b565b6009880191906139d7565b6123a4818761565c565b6001600160a01b0389165f908152600987016020526040812080549091906123cd9084906155c7565b90915550879050600986015f6123e1610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f205f82825461240e919061565c565b9091555050604080516001600160a01b038a16815260208101899052908101879052606081018290527fc659bef2facfde65b659c8c5160cf21ac8232b38f8331aac0cea195e1d9296659060800160405180910390a15050505050505050565b5f805f61247a846136ba565b9092509050610aa3818361565c565b612491612b79565b5f61249a61293d565b90505f6124a5611f12565b90506124af610e5f565b6001600160a01b0316846001600160a01b0316036124e05760405163d3c4f33360e01b815260040160405180910390fd5b80515f5b8181101561253f57856001600160a01b03168382815181106125085761250861557f565b60200260200101516001600160a01b031603612537576040516360f7af0b60e11b815260040160405180910390fd5b6001016124e4565b5061254d6002840186613b2a565b61256a57604051631cf57a9f60e11b815260040160405180910390fd5b825460408051633a0df78d60e11b815290515f926001600160a01b03169163741bef1a9160048083019260209291908290030181865afa1580156125b0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125d491906156f2565b604051635670bcc760e11b81529091506001600160a01b0382169063ace1798e906126039089906004016151d4565b602060405180830381865afa15801561261e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612642919061570d565b5f036126615760405163fb94c4ed60e01b815260040160405180910390fd5b61266f600985018787612c1e565b7f252fb22f1e5dcdba04908f13259852204aead54fea1342d028eb2f49510bee978660405161269e91906151d4565b60405180910390a1505050505050565b5f6126b7613b3e565b805490915060ff600160401b82041615906001600160401b03165f811580156126dd5750825b90505f826001600160401b031660011480156126f85750303b155b905081158015612706575080155b156127245760405163f92ee8a960e01b815260040160405180910390fd5b84546001600160401b0319166001178555831561274d57845460ff60401b1916600160401b1785555b5f61275661293d565b90505f6127696080890160608a0161510d565b6001600160a01b0316148061279557505f61278a60a0890160808a0161510d565b6001600160a01b0316145b806127b757505f6127ac60c0890160a08a0161510d565b6001600160a01b0316145b156127d557604051639fabe1c160e01b815260040160405180910390fd5b6127e5608088016060890161510d565b81546001600160a01b0319166001600160a01b039190911617815561281060e0880160c0890161510d565b6001820180546001600160a01b0319166001600160a01b039290921691909117905561285b8161284660a08a0160808b0161510d565b61285660c08b0160a08c0161510d565b613766565b6128e561286b6020890189615757565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506128ac9250505060408a018a615757565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250613b6292505050565b6128fa6128f5602089018961510d565b613b74565b508315610bca57845460ff60401b191685556040517fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29061269e90600190615825565b7f3c2bbd5b01c023780ac7877400fd851b17fd98c152afdb1efc02015acd68a30090565b5f610a54825490565b6001600160a01b0381165f9081526001830160209081526040808320815160608101835290546001600160801b03811682526001600160401b03600160801b8204811694830194909452600160c01b9004909216908201526129d4816129cf816132cd565b6132fe565b6001600160a01b0384165f90815260208690526040902054610aa3919061565c565b5f612a0282600a61591c565b612a0c84866155da565b610aa39190615605565b5f610d388383613b85565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0090565b5f610d38612a516107e9565b612a5c9060016155c7565b612a675f600a61591c565b612a6f610bd2565b612a7991906155c7565b85919085612b1e565b610acc8383836001613bab565b5f610a54826001613ab1565b5f80612aa561293d565b80546040516301646b0560e61b81529192506001600160a01b03169063591ac14090612ad59033906004016151d4565b602060405180830381865afa158015612af0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b14919061592a565b61ffff1691505090565b5f80612b2b868686613c7c565b90506001836002811115612b4157612b4161594b565b148015612b5d57505f8480612b5857612b586155f1565b868809115b15612b7057612b6d6001826155c7565b90505b95945050505050565b612b8161293d565b5460408051638da5cb5b60e01b815290516001600160a01b0390921691638da5cb5b916004808201926020929091908290030181865afa158015612bc7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612beb91906156f2565b6001600160a01b0316336001600160a01b031614612c1c57604051635fc483c560e01b815260040160405180910390fd5b565b64e8d4a510006001600160401b0382161115612c4d576040516304bba2fb60e51b815260040160405180910390fd5b612c5883835f613d25565b6001600160a01b0382165f8181526001850160205260409081902080546001600160c01b0316600160c01b6001600160401b03861602179055517f5577d4c8f6e5397effa5c71df8fe221e1162e18aaa0aabe87026cfb0c676215090612cbf908490615825565b60405180910390a2505050565b5f612cd7848461217e565b90505f1981146116b15781811015612d0857828183604051637dc7a0d960e11b8152600401610daf939291906156c3565b6116b184848484035f613bab565b6001600160a01b038316612d3f575f604051634b637e8f60e11b8152600401610daf91906151d4565b6001600160a01b038216612d68575f60405163ec442f0560e01b8152600401610daf91906151d4565b610acc838383613e89565b7f0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e0090565b5f612da061293d565b8054604080516341ba27eb60e01b815290519293506001600160a01b03909116916341ba27eb916004808201926020929091908290030181865afa158015612dea573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e0e919061595f565b6001600160401b0316421015612e375760405163abdc9be160e01b815260040160405180910390fd5b50565b5f80612e4e612e47612a9b565b8690613385565b9050336001600160a01b03841614612e6b57612e6b833387612ccc565b8315612eba57612eb7600987015f612e81610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f2054855f8489612eaf919061565c565b929190612b1e565b91505b8015612ed8576001860154612ed8906001600160a01b031682613fac565b612ee28386613fe0565b94509492505050565b5f612ef583614014565b90508060400151612f0886600201612961565b612f1291906155c7565b612f1d9060016155c7565b815114612f3d57604051634ec4810560e11b815260040160405180910390fd5b335f908152600d8601602052604090205460ff16158015612f9f5750612f61610e5f565b6001600160a01b0316836001835f0151612f7b919061565c565b81518110612f8b57612f8b61557f565b60200260200101516001600160a01b031614155b15612fbd57604051631bad141f60e31b815260040160405180910390fd5b8051612fca9084906140b7565b835f612fd7610440610e5f565b90505f5b835181108015612fea57508215155b15613200575f8682815181106130025761300261557f565b6020026020010151905061304185602001518660400151613021610e5f565b61302e60028e018661353d565b6001600160a01b0386169392919061414d565b5f61304f60098b018361296a565b9050805f0361305f5750506131ee565b5f61306983610ef3565b9050805f0361307a575050506131ee565b5f836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156130b7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130db9190615593565b90505f6130e6610e5f565b6001600160a01b0316856001600160a01b031603613105575086613120565b61311d8388613112610d3f565b8b929190865f613ae5565b90505b80841061315f576001600160a01b0385165f90815260098e0160205260408120805491995082918a9061315490849061565c565b909155506131c59050565b5f61316a858361565c565b90506131838489613179610d3f565b84929190876141db565b9850849150818e6009015f015f886001600160a01b03166001600160a01b031681526020019081526020015f205f8282546131be919061565c565b9091555050505b80896060015187815181106131dc576131dc61557f565b60200260200101818152505050505050505b806131f88161573f565b915050612fdb565b505f5b835181101561328d575f846060015182815181106132235761322361557f565b6020026020010151111561328557613285858560600151838151811061324b5761324b61557f565b60200260200101518884815181106132655761326561557f565b60200260200101516001600160a01b031661384c9092919063ffffffff16565b600101613203565b50836001600160a01b03165f80516020615ba1833981519152878786606001516040516132bc9392919061597a565b60405180910390a250505050505050565b60208101515f906001600160401b03166132f464e8d4a510006132ef85614238565b61426d565b610a5491906155c7565b5f81421061330d57505f610a54565b5f83602001516001600160401b031642613327919061565c565b90505f8161333486614238565b61333e91906155da565b855190915064e8d4a510009061335d906001600160801b0316836155da565b6133679190615605565b855161337c91906001600160801b031661565c565b92505050610a54565b5f610d3883836127106001612b1e565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016148061341b57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661340f5f80516020615b5a833981519152546001600160a01b031690565b6001600160a01b031614155b15612c1c5760405163703e46dd60e11b815260040160405180910390fd5b612e37612b79565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa92505050801561349b575060408051601f3d908101601f191682019092526134989181019061570d565b60015b6134ba5781604051634c9c8ce360e01b8152600401610daf91906151d4565b5f80516020615b5a83398151915281146134ea57604051632a87526960e21b815260048101829052602401610daf565b610acc838361428f565b306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614612c1c5760405163703e46dd60e11b815260040160405180910390fd5b5f610d38836001600160a01b0384166142e4565b5f61355a61293d565b6001600160a01b0385165f908152600782016020526040902054909150156135955760405163caf865c160e01b815260040160405180910390fd5b5f8160050184815481106135ab576135ab61557f565b5f9182526020808320909101546001600160a01b031680835260098501909152604090912054909150158015906135e0575082155b156135fe576040516305ec751560e51b815260040160405180910390fd5b6136098460016155c7565b6001600160a01b0386165f9081526007840160205260409020556005820180548691908690811061363c5761363c61557f565b5f9182526020918290200180546001600160a01b0319166001600160a01b03938416179055604080518484168152928816918301919091527f9e147d339c63698deb55c3d0d44ed3eba29bac2a068a88c4bc5bde17d6331e19910160405180910390a15050505050565b5f610d38836001600160a01b0384166142fb565b5f806136c58361215c565b91506136d96136d26138a2565b8390613385565b9050915091565b6136ea33846143de565b8015613708576001850154613708906001600160a01b031682613fac565b6137128285613fac565b816001600160a01b0316336001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d785876040516137579291906156e4565b60405180910390a35050505050565b6001600160a01b0381165f908152600b8401602052604090205460ff16156137a157604051631f160d3160e11b815260040160405180910390fd5b6001600160a01b0382165f908152600c8401602052604090205460ff16156137dc57604051632748f32960e21b815260040160405180910390fd5b6001600160a01b038181165f818152600b8601602090815260408083208054600160ff199182168117909255958816808552600c8a0190935281842080549096161790945592517fd6c91941062a66dc4c4344f6b10af4b565b256816a2f9080ba7f83e1d6a2bdc69190a3505050565b610acc8363a9059cbb60e01b848460405160240161386b9291906159d4565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614492565b5f806138ac61293d565b8054604051636034d9f560e01b81529192506001600160a01b031690636034d9f590612ad59033906004016151d4565b5f610a54826001612a45565b6138f28787614563565b6138fd86868661460f565b826001600160a01b0316866001600160a01b0316336001600160a01b03165f80516020615b3a83398151915285856040516139399291906156e4565b60405180910390a450505050505050565b6116b1846323b872dd60e01b85858560405160240161386b939291906159ed565b5f6001600160801b038211156139d35760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b6064820152608401610daf565b5090565b806001600160801b03165f03613a005760405163d11b25af60e01b815260040160405180910390fd5b613a0b838383613d25565b816001600160a01b03167f693ffe037fd29f4846b006bd3ada57d4fd4c3622277227342f0e4fed9011dc2082604051612cbf919061541a565b806001600160801b03165f03613a6d5760405163d11b25af60e01b815260040160405180910390fd5b613a78838383614995565b816001600160a01b03167f5f4e7177e0f8e013ddb6d29e468fa7a45f8df4e00e7895b7f20c5979cab21c6c82604051612cbf919061541a565b5f610d38613ac082600a61591c565b613ac8610bd2565b613ad291906155c7565b613ada6107e9565b612a799060016155c7565b5f80613aff86613af687600a61591c565b8a919086612b1e565b90508615613b1b57613b1381888686614a73565b915050613b20565b5f9150505b9695505050505050565b5f610d38836001600160a01b038416614aa2565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0090565b613b6a614ae9565b6110138282614b0e565b613b7c614ae9565b612e3781614b3e565b5f825f018281548110613b9a57613b9a61557f565b905f5260205f200154905092915050565b5f613bb4612a21565b90506001600160a01b038516613bdf575f60405163e602df0560e01b8152600401610daf91906151d4565b6001600160a01b038416613c08575f604051634a1406b160e11b8152600401610daf91906151d4565b6001600160a01b038086165f9081526001830160209081526040808320938816835292905220839055811561215557836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258560405161375791815260200190565b5f80805f19858709858702925082811083820303915050805f03613cb357838281613ca957613ca96155f1565b0492505050610d38565b808411613cbe575f80fd5b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b6001600160a01b0382165f9081526001840160209081526040808320815160608101835290546001600160801b03811682526001600160401b03600160801b8204811694830194909452600160c01b90049092169082015290613d87826132cd565b90505f613db0846001600160801b0316613da185856132fe565b613dab91906155c7565b61396b565b6001600160801b03811684529050613dc742614bab565b6001600160401b03166020808501919091526001600160a01b0386165f908152908790526040812080546001600160801b0387169290613e089084906155c7565b909155505050506001600160a01b03929092165f9081526001939093016020908152604093849020835181549285015194909501516001600160801b039095166001600160c01b031990921691909117600160801b6001600160401b0394851602176001600160c01b0316600160c01b939094169290920292909217905550565b5f613e92612a21565b90506001600160a01b038416613ec05781816002015f828254613eb591906155c7565b90915550613f1d9050565b6001600160a01b0384165f9081526020829052604090205482811015613eff5784818460405163391434e360e21b8152600401610daf939291906156c3565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b038316613f3b576002810180548390039055613f59565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051613f9e91815260200190565b60405180910390a350505050565b6001600160a01b038216613fd5575f60405163ec442f0560e01b8152600401610daf91906151d4565b6110135f8383613e89565b6001600160a01b038216614009575f604051634b637e8f60e11b8152600401610daf91906151d4565b611013825f83613e89565b61403d60405180608001604052805f8152602001606081526020015f8152602001606081525090565b5f614046611f12565b90505f83519050604051806080016040528082815260200183815260200183518152602001826001600160401b03811115614083576140836151e8565b6040519080825280602002602001820160405280156140ac578160200160208202803683370190505b509052949350505050565b5f5b81811015610acc575f6140cd8260016155c7565b90505b82811015614144578381815181106140ea576140ea61557f565b60200260200101516001600160a01b031684838151811061410d5761410d61557f565b60200260200101516001600160a01b03160361413c576040516323271fb560e11b815260040160405180910390fd5b6001016140d0565b506001016140b9565b808061416a5750816001600160a01b0316856001600160a01b0316145b612155575f805b848110156141bc57866001600160a01b03168682815181106141955761419561557f565b60200260200101516001600160a01b0316036141b457600191506141bc565b600101614171565b5080610bca5760405163c1ab6dc160e01b815260040160405180910390fd5b5f806141e883600a61591c565b6141f287896155da565b6141fc9190615605565b9050841561422c578461421085600a61591c565b61421a90836155da565b6142249190615605565b915050612b70565b505f9695505050505050565b5f81604001516001600160401b03165f1461425757816040015161425e565b64174876e8005b6001600160401b031692915050565b5f81600161427b82866155c7565b614285919061565c565b610d389190615605565b61429882614c12565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156142dc57610acc8282614c6c565b611013614c91565b5f9081526001919091016020526040902054151590565b5f81815260018301602052604081205480156143d5575f61431d60018361565c565b85549091505f906143309060019061565c565b905081811461438f575f865f01828154811061434e5761434e61557f565b905f5260205f200154905080875f01848154811061436e5761436e61557f565b5f918252602080832090910192909255918252600188019052604090208390555b85548690806143a0576143a0615a11565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610a54565b5f915050610a54565b5f6143e761293d565b90506143f1610e5f565b6001600160a01b031663e75b3ae784846040518363ffffffff1660e01b815260040161441e9291906159d4565b5f604051808303815f87803b158015614435575f80fd5b505af1158015614447573d5f803e3d5ffd5b5050505081816009015f015f61445b610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f205f82825461448891906155c7565b9091555050505050565b5f6144e6826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614cb09092919063ffffffff16565b805190915015610acc57808060200190518101906145049190615724565b610acc5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610daf565b5f61456c61293d565b9050614576610e5f565b6001600160a01b03166320c582be3084866040518463ffffffff1660e01b81526004016145a5939291906159ed565b5f604051808303815f87803b1580156145bc575f80fd5b505af11580156145ce573d5f803e3d5ffd5b5050505082816009015f015f6145e2610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f205f828254614488919061565c565b5f61461861293d565b90505f614623611f12565b80519091505f61463560028501612961565b90505f61464282846155c7565b6001600160401b03811115614659576146596151e8565b604051908082528060200260200182016040528015614682578160200160208202803683370190505b5090505f61469083856155c7565b6001600160401b038111156146a7576146a76151e8565b6040519080825280602002602001820160405280156146d0578160200160208202803683370190505b5090505f5b848110156147fb575f61470d8783815181106146f3576146f361557f565b60200260200101518960090161296a90919063ffffffff16565b905061471b8a828b5f612b1e565b84838151811061472d5761472d61557f565b60200260200101818152505086828151811061474b5761474b61557f565b60200260200101518383815181106147655761476561557f565b60200260200101906001600160a01b031690816001600160a01b0316815250508382815181106147975761479761557f565b6020026020010151886009015f015f8985815181106147b8576147b861557f565b60200260200101516001600160a01b03166001600160a01b031681526020019081526020015f205f8282546147ed919061565c565b9091555050506001016146d5565b505f5b838110156148f3575f61481186836155c7565b90505f61482160028a0184612a16565b90505f61483160098b018361296a565b905061483f8c828d5f612b1e565b8684815181106148515761485161557f565b602002602001018181525050818584815181106148705761487061557f565b60200260200101906001600160a01b031690816001600160a01b0316815250508583815181106148a2576148a261557f565b60200260200101518a6009015f015f846001600160a01b03166001600160a01b031681526020019081526020015f205f8282546148df919061565c565b9091555050600190930192506147fe915050565b505f5b8151811015614957578281815181106149115761491161557f565b60200260200101515f1461494f5761494f8a8483815181106149355761493561557f565b60200260200101518484815181106132655761326561557f565b6001016148f6565b50886001600160a01b03165f80516020615ba18339815191528983856040516149829392919061597a565b60405180910390a2505050505050505050565b6001600160a01b0382165f9081526001840160209081526040808320815160608101835290546001600160801b03811682526001600160401b03600160801b8204811694830194909452600160c01b900490921690820152906149f7826132cd565b90505f614a1b846001600160801b0316614a1185856132fe565b613dab919061565c565b6001600160801b03811684529050614a3242614bab565b6001600160401b03166020808501919091526001600160a01b0386165f908152908790526040812080546001600160801b0387169290613e0890849061565c565b5f831580614a7f575084155b15614a8b57505f610aa3565b612b70614a9984600a61591c565b86908685612b1e565b5f614aad83836142e4565b614ae257508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610a54565b505f610a54565b614af1614cbe565b612c1c57604051631afcd79f60e31b815260040160405180910390fd5b614b16614ae9565b5f614b1f612a21565b905060038101614b2f8482615a69565b50600481016116b18382615a69565b614b46614ae9565b5f614b4f612d73565b90505f80614b5c84614cd7565b9150915081614b6c576012614b6e565b805b83546001600160a81b031916600160a01b60ff92909216919091026001600160a01b031916176001600160a01b0394909416939093179091555050565b5f6001600160401b038211156139d35760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660448201526534206269747360d01b6064820152608401610daf565b806001600160a01b03163b5f03614c3e5780604051634c9c8ce360e01b8152600401610daf91906151d4565b5f80516020615b5a83398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b6060610d388383604051806060016040528060278152602001615b7a60279139614dad565b3415612c1c5760405163b398979f60e01b815260040160405180910390fd5b6060610aa384845f85614e17565b5f614cc7613b3e565b54600160401b900460ff16919050565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290515f918291829182916001600160a01b03871691614d1d91615b23565b5f60405180830381855afa9150503d805f8114614d55576040519150601f19603f3d011682016040523d82523d5f602084013e614d5a565b606091505b5091509150818015614d6e57506020815110155b15614da1575f81806020019051810190614d88919061570d565b905060ff8111614d9f576001969095509350505050565b505b505f9485945092505050565b60605f80856001600160a01b031685604051614dc99190615b23565b5f60405180830381855af49150503d805f8114614e01576040519150601f19603f3d011682016040523d82523d5f602084013e614e06565b606091505b5091509150613b2086838387614eee565b606082471015614e785760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610daf565b5f80866001600160a01b03168587604051614e939190615b23565b5f6040518083038185875af1925050503d805f8114614ecd576040519150601f19603f3d011682016040523d82523d5f602084013e614ed2565b606091505b5091509150614ee387838387614eee565b979650505050505050565b60608315614f5c5782515f03614f55576001600160a01b0385163b614f555760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610daf565b5081610aa3565b610aa38383815115614f715781518083602001fd5b8060405162461bcd60e51b8152600401610daf91905b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b5f60208284031215614fcc575f80fd5b5035919050565b6001600160a01b0381168114612e37575f80fd5b5f8060408385031215614ff8575f80fd5b823561500381614fd3565b946020939093013593505050565b6001600160401b0381168114612e37575f80fd5b5f8060408385031215615036575f80fd5b823561504181614fd3565b9150602083013561505181615011565b809150509250929050565b5f8083601f84011261506c575f80fd5b5081356001600160401b03811115615082575f80fd5b6020830191508360208260051b850101111561509c575f80fd5b9250929050565b5f805f80604085870312156150b6575f80fd5b84356001600160401b038111156150cb575f80fd5b6150d78782880161505c565b90955093505060208501356001600160401b038111156150f5575f80fd5b6151018782880161505c565b95989497509550505050565b5f6020828403121561511d575f80fd5b8135610d3881614fd3565b5f805f6060848603121561513a575f80fd5b833561514581614fd3565b9250602084013561515581614fd3565b929592945050506040919091013590565b5f805f805f6080868803121561517a575f80fd5b8535945060208601356001600160401b03811115615196575f80fd5b6151a28882890161505c565b90955093505060408601356151b681614fd3565b915060608601356151c681614fd3565b809150509295509295909350565b6001600160a01b0391909116815260200190565b634e487b7160e01b5f52604160045260245ffd5b5f806040838503121561520d575f80fd5b823561521881614fd3565b915060208301356001600160401b03811115615232575f80fd5b8301601f81018513615242575f80fd5b80356001600160401b0381111561525b5761525b6151e8565b604051601f8201601f19908116603f011681016001600160401b0381118282101715615289576152896151e8565b6040528181528282016020018710156152a0575f80fd5b816020840160208301375f602083830101528093505050509250929050565b8015158114612e37575f80fd5b5f805f606084860312156152de575f80fd5b83356152e981614fd3565b925060208401356152f981615011565b91506040840135615309816152bf565b809150509250925092565b5f8060408385031215615325575f80fd5b82359150602083013561505181614fd3565b5f8060208385031215615348575f80fd5b82356001600160401b0381111561535d575f80fd5b6153698582860161505c565b90969095509350505050565b602080825282518282018190525f918401906040840190835b818110156153ac57835183526020938401939092019160010161538e565b509095945050505050565b5f805f606084860312156153c9575f80fd5b83356153d481614fd3565b925060208401356152f981614fd3565b5f602082840312156153f4575f80fd5b81356001600160401b03811115615409575f80fd5b820160a08185031215610d38575f80fd5b6001600160801b0391909116815260200190565b5f805f60608486031215615440575f80fd5b83359250602084013561545281614fd3565b9150604084013561530981614fd3565b5f8151808452602084019350602083015f5b8281101561549b5781516001600160a01b0316865260209586019590910190600101615474565b5093949350505050565b602081525f610d386020830184615462565b5f805f606084860312156154c9575f80fd5b83356154d481614fd3565b925060208401359150604084013561530981614fd3565b5f80604083850312156154fc575f80fd5b823561550781614fd3565b9150602083013561505181614fd3565b5f805f60608486031215615529575f80fd5b833561553481614fd3565b95602085013595506040909401359392505050565b5f60208284031215615559575f80fd5b81356001600160401b0381111561556e575f80fd5b820160e08185031215610d38575f80fd5b634e487b7160e01b5f52603260045260245ffd5b5f602082840312156155a3575f80fd5b815160ff81168114610d38575f80fd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115610a5457610a546155b3565b8082028115828204841417610a5457610a546155b3565b634e487b7160e01b5f52601260045260245ffd5b5f8261561f57634e487b7160e01b5f52601260045260245ffd5b500490565b600181811c9082168061563857607f821691505b60208210810361565657634e487b7160e01b5f52602260045260245ffd5b50919050565b81810381811115610a5457610a546155b3565b5f6020828403121561567f575f80fd5b8135610d38816152bf565b5f61ffff821661ffff81036156a1576156a16155b3565b60010192915050565b60ff8181168382160190811115610a5457610a546155b3565b6001600160a01b039390931683526020830191909152604082015260600190565b918252602082015260400190565b5f60208284031215615702575f80fd5b8151610d3881614fd3565b5f6020828403121561571d575f80fd5b5051919050565b5f60208284031215615734575f80fd5b8151610d38816152bf565b5f60018201615750576157506155b3565b5060010190565b5f808335601e1984360301811261576c575f80fd5b8301803591506001600160401b03821115615785575f80fd5b60200191503681900382131561509c575f80fd5b6001600160a01b03868116825260208201869052841660408201526080606082018190528101829052818360a08301375f81830160a090810191909152601f909201601f19160101949350505050565b6001600160601b0319606093841b811682529190921b16601482015260280190565b5f600160ff1b820161581f5761581f6155b3565b505f0390565b6001600160401b0391909116815260200190565b6001815b600184111561587457808504811115615858576158586155b3565b600184161561586657908102905b60019390931c92800261583d565b935093915050565b5f8261588a57506001610a54565b8161589657505f610a54565b81600181146158ac57600281146158b6576158d2565b6001915050610a54565b60ff8411156158c7576158c76155b3565b50506001821b610a54565b5060208310610133831016604e8410600b84101617156158f5575081810a610a54565b6159015f198484615839565b805f1904821115615914576159146155b3565b029392505050565b5f610d3860ff84168361587c565b5f6020828403121561593a575f80fd5b815161ffff81168114610d38575f80fd5b634e487b7160e01b5f52602160045260245ffd5b5f6020828403121561596f575f80fd5b8151610d3881615011565b838152606060208201525f6159926060830185615462565b8281036040840152835180825260208086019201905f5b818110156159c75783518352602093840193909201916001016159a9565b5090979650505050505050565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b5f52603160045260245ffd5b601f821115610acc57805f5260205f20601f840160051c81016020851015615a4a5750805b601f840160051c820191505b81811015612155575f8155600101615a56565b81516001600160401b03811115615a8257615a826151e8565b615a9681615a908454615624565b84615a25565b6020601f821160018114615ac8575f8315615ab15750848201515b5f19600385901b1c1916600184901b178455612155565b5f84815260208120601f198516915b82811015615af75787850151825560209485019460019092019101615ad7565b5084821015615b1457868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b5f82518060208501845e5f92019182525091905056fefbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c656486bcb277da75a9fbb738b8bb82beb731d82a0a89516b848730df92849f966bf0a2646970667358221220958dddfaf5841522c4d7d2b3154be2f884ebbf892ce000a781919beaf686978e64736f6c634300081a0033
Deployed Bytecode
0x608060405260043610610222575f3560e01c806301e1d1141461022657806306fdde031461024d57806307a2d13a1461026e578063095ea7b31461028d5780630a28a477146102bc5780630b983a74146102db5780630d9a6b35146102fc57806315450da01461031057806318160ddd1461032f57806319f27b3b1461034357806323b872dd14610362578063313ce5671461038157806331e95162146103a757806338d52e0f146103c6578063402d267d146103e7578063403dd3bc1461040757806341976e09146104265780634cdad506146104455780634f1ef2861461046457806352d1902d14610477578063602ecae51461048b5780636cd611be146104aa5780636e553f65146104c957806370a08231146104e85780637784c685146105075780637b8b8b74146105335780637facd79b1461055257806394bf804d1461057157806395d89b4114610590578063a7528a03146105a4578063a9059cbb146105c7578063ad3cb1cc146105e6578063b3d7f6b914610616578063b460af9414610635578063b58eb63f14610654578063ba08765214610675578063badd8b2d14610694578063c5e6a767146106b3578063c63d75b6146103e7578063c6e6f592146106d2578063ce96cb77146106f1578063d905777e14610710578063dd62ed3e1461072f578063ddda679b1461074e578063e66667331461076d578063ef8b30f71461078c578063fcb99905146107ab578063fd694144146107ca575b5f80fd5b348015610231575f80fd5b5061023a6107e9565b6040519081526020015b60405180910390f35b348015610258575f80fd5b506102616109ab565b6040516102449190614f87565b348015610279575f80fd5b5061023a610288366004614fbc565b610a49565b348015610298575f80fd5b506102ac6102a7366004614fe7565b610a5a565b6040519015158152602001610244565b3480156102c7575f80fd5b5061023a6102d6366004614fbc565b610a71565b3480156102e6575f80fd5b506102fa6102f5366004615025565b610aab565b005b348015610307575f80fd5b5061023a610ad1565b34801561031b575f80fd5b506102fa61032a3660046150a3565b610b0b565b34801561033a575f80fd5b5061023a610bd2565b34801561034e575f80fd5b506102fa61035d36600461510d565b610be6565b34801561036d575f80fd5b506102ac61037c366004615128565b610d1a565b34801561038c575f80fd5b50610395610d3f565b60405160ff9091168152602001610244565b3480156103b2575f80fd5b5061023a6103c1366004615166565b610d68565b3480156103d1575f80fd5b506103da610e5f565b60405161024491906151d4565b3480156103f2575f80fd5b5061023a61040136600461510d565b505f1990565b348015610412575f80fd5b5061023a61042136600461510d565b610e79565b348015610431575f80fd5b5061023a61044036600461510d565b610ef3565b348015610450575f80fd5b5061023a61045f366004614fbc565b610fd5565b6102fa6104723660046151fc565b610ff8565b348015610482575f80fd5b5061023a611017565b348015610496575f80fd5b506102fa6104a53660046152cc565b611032565b3480156104b5575f80fd5b506102fa6104c436600461510d565b6112bc565b3480156104d4575f80fd5b5061023a6104e3366004615314565b6113f2565b3480156104f3575f80fd5b5061023a61050236600461510d565b6114ba565b348015610512575f80fd5b50610526610521366004615337565b6114e3565b6040516102449190615375565b34801561053e575f80fd5b506102fa61054d3660046153b7565b611572565b34801561055d575f80fd5b506102fa61056c3660046153e4565b6116b7565b34801561057c575f80fd5b5061023a61058b366004615314565b611d44565b34801561059b575f80fd5b50610261611e24565b3480156105af575f80fd5b506105ba62093a8081565b604051610244919061541a565b3480156105d2575f80fd5b506102ac6105e1366004614fe7565b611e40565b3480156105f1575f80fd5b50610261604051806040016040528060058152602001640352e302e360dc1b81525081565b348015610621575f80fd5b5061023a610630366004614fbc565b611e4d565b348015610640575f80fd5b5061023a61064f36600461542e565b611e7e565b34801561065f575f80fd5b50610668611f12565b60405161024491906154a5565b348015610680575f80fd5b5061023a61068f36600461542e565b611f7b565b34801561069f575f80fd5b506102fa6106ae366004615128565b612003565b3480156106be575f80fd5b506102fa6106cd3660046154b7565b61207d565b3480156106dd575f80fd5b5061023a6106ec366004614fbc565b61215c565b3480156106fc575f80fd5b5061023a61070b36600461510d565b612167565b34801561071b575f80fd5b5061023a61072a36600461510d565b612174565b34801561073a575f80fd5b5061023a6107493660046154eb565b61217e565b348015610759575f80fd5b5061023a610768366004615166565b6121b8565b348015610778575f80fd5b506102fa610787366004615517565b612293565b348015610797575f80fd5b5061023a6107a6366004614fbc565b61246e565b3480156107b6575f80fd5b506102fa6107c5366004615025565b612489565b3480156107d5575f80fd5b506102fa6107e4366004615549565b6126ae565b5f806107f361293d565b90505f806107ff611f12565b90505f61080d610440610e5f565b82519091505f61081f60028701612961565b90505f600987018161082f610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f205490505f5b83811015610922575f86828151811061086e5761086e61557f565b602002602001015190505f61088f828b60090161296a90919063ffffffff16565b905080156109185761090b6108a383610ef3565b836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108df573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109039190615593565b8391906129f6565b610915908a6155c7565b98505b5050600101610853565b505f5b82811015610976575f61093b60028a0183612a16565b90505f61094b60098b018361296a565b9050801561096c5761095f6108a383610ef3565b610969908a6155c7565b98505b5050600101610925565b50808461098b670de0b6b3a7640000896155da565b6109959190615605565b61099f91906155c7565b97505050505050505090565b60605f6109b6612a21565b90508060030180546109c790615624565b80601f01602080910402602001604051908101604052809291908181526020018280546109f390615624565b8015610a3e5780601f10610a1557610100808354040283529160200191610a3e565b820191905f5260205f20905b815481529060010190602001808311610a2157829003601f168201915b505050505091505090565b5f610a54825f612a45565b92915050565b5f33610a67818585612a82565b5060019392505050565b5f80610a7c83612a8f565b90505f610aa3612710610a8d612a9b565b610a999061271061565c565b8491906001612b1e565b949350505050565b610ab3612b79565b5f610abc61293d565b9050610acc600982018484612c1e565b505050565b5f610ada61293d565b6009015f610ae6610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f2054905090565b610b13612b79565b5f610b1c61293d565b9050838214610b3e57604051634ec4810560e11b815260040160405180910390fd5b5f5b84811015610bca57838382818110610b5a57610b5a61557f565b9050602002016020810190610b6f919061566f565b82600d015f888885818110610b8657610b8661557f565b9050602002016020810190610b9b919061510d565b6001600160a01b0316815260208101919091526040015f20805460ff1916911515919091179055600101610b40565b505050505050565b5f80610bdc612a21565b6002015492915050565b610bee612b79565b5f610bf761293d565b6001600160a01b0383165f90815260078201602052604081205491925003610c3257604051630b3cfa8f60e01b815260040160405180910390fd5b6040805180820182526001600160a01b0384165f9081526007840160205291909120548190610c639060019061565c565b6001600160801b03168152602001610c7e62093a80426155c7565b6001600160801b0316905260048201805460068401915f9162010000900461ffff16906002610cac8361568a565b825461ffff9182166101009390930a92830292820219169190911790915516815260208082019290925260409081015f9081208451948401516001600160801b03908116600160801b029516949094179093556001600160a01b039094168252600790920190915290812055565b5f33610d27858285612ccc565b610d32858585612d16565b60019150505b9392505050565b5f80610d49612d73565b90505f8154610d629190600160a01b900460ff166156aa565b91505090565b5f610d71612d97565b5f610d7a61293d565b90505f610d8684612174565b905080881115610db857838882604051632e52afbb60e21b8152600401610daf939291906156c3565b60405180910390fd5b610dc188610fd5565b9250610dcf82895f87612e3a565b5050610e1082848989808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152508b9250612eeb915050565b836001600160a01b0316856001600160a01b0316336001600160a01b03165f80516020615b3a833981519152868c604051610e4c9291906156e4565b60405180910390a4505095945050505050565b5f80610e69612d73565b546001600160a01b031692915050565b5f80610e8361293d565b6001600160a01b0384165f908152600a90910160209081526040808320815160608101835290546001600160801b03811682526001600160401b03600160801b8204811694830194909452600160c01b9004909216908201529150610ee7826132cd565b9050610aa382826132fe565b5f80610efd61293d565b5460408051633a0df78d60e11b815290516001600160a01b039092169163741bef1a916004808201926020929091908290030181865afa158015610f43573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f6791906156f2565b604051635670bcc760e11b81529091506001600160a01b0382169063ace1798e90610f969086906004016151d4565b602060405180830381865afa158015610fb1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d38919061570d565b5f80610fe9610fe2612a9b565b8490613385565b9050610d38610288828561565c565b611000613395565b61100982613439565b6110138282613441565b5050565b5f6110206134f4565b505f80516020615b5a83398151915290565b5f61103b61293d565b9050611045610e5f565b6001600160a01b0316846001600160a01b0316036110765760405163d3c4f33360e01b815260040160405180910390fd5b335f908152600b8201602052604090205460ff166110a75760405163a84178ab60e01b815260040160405180910390fd5b6110b4600282018561353d565b156110d257604051631cf57a9f60e11b815260040160405180910390fd5b60058101545f6110e6600984018787612c1e565b5f5b8281101561113957866001600160a01b031684600501828154811061110f5761110f61557f565b5f918252602090912001546001600160a01b0316036111315760019150611139565b6001016110e8565b50806112695760408051808201909152600484015461ffff808216808452620100009092041660208301819052111561121e57805161ffff165f9081526006850160209081526040918290208251808401909352546001600160801b038082168452600160801b9091041690820181905242111561121c5760048501805460068701915f9161ffff1690826111cd8361568a565b82546101009290920a61ffff81810219909316918316021790915516815260208101919091526040015f9081205580516112129089906001600160801b031688613551565b5050505050505050565b505b506005830180546001810182555f828152602080822090920180546001600160a01b0319166001600160a01b038b169081179091559254928152600786019091526040902055610bca565b6001600160a01b0386165f9081526007840160205260409020541580156112a357604051630b3cfa8f60e01b815260040160405180910390fd5b6040516360f7af0b60e11b815260040160405180910390fd5b6112c4612b79565b5f6112cd61293d565b6001600160a01b0383165f90815260098201602052604090205490915015611308576040516305ec751560e51b815260040160405180910390fd5b6001600160a01b0382165f908152600a82016020908152604091829020825160608101845290546001600160801b03811682526001600160401b03600160801b8204811693830193909352600160c01b900490911691810191909152429061136f906132cd565b1061138d5760405163fda6d69360e01b815260040160405180910390fd5b61139a60028201836136a6565b6113b75760405163081fcdbf60e21b815260040160405180910390fd5b7ffc9138846a97b86614d19b78419b88e555c50bbd80b03feffd6264cd43064380826040516113e691906151d4565b60405180910390a15050565b5f806113fc61293d565b805460408051635c975abb60e01b815290519293506001600160a01b0390911691635c975abb916004808201926020929091908290030181865afa158015611446573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061146a9190615724565b15611488576040516313d0ff5960e31b815260040160405180910390fd5b5f80611493866136ba565b90925090506114a2818361565c565b93506114b183858888856136e0565b50505092915050565b5f806114c4612a21565b6001600160a01b039093165f9081526020939093525050604090205490565b606081806001600160401b038111156114fe576114fe6151e8565b604051908082528060200260200182016040528015611527578160200160208202803683370190505b5091505f5b8181101561156a575f8585836115418161573f565b94508181106115525761155261557f565b9050602002013590508054602083028501525061152c565b505092915050565b61157a612b79565b5f61158361293d565b90506001600160a01b03841615806115a257506001600160a01b038316155b156115c057604051639fabe1c160e01b815260040160405180910390fd5b81156115d6576115d1818585613766565b6116b1565b6001600160a01b0383165f908152600b8201602052604090205460ff16611610576040516335f85eb560e11b815260040160405180910390fd5b6001600160a01b0384165f908152600c8201602052604090205460ff1661164a57604051635819892360e11b815260040160405180910390fd5b6001600160a01b038084165f818152600b840160209081526040808320805460ff19908116909155948916808452600c8701909252808320805490951690945592517f88ecee496061ddc38d88503f7cf6a1f4f6ade60ee216c946c5a0e8de6049595c9190a35b50505050565b6116bf612b79565b5f6116c861293d565b90506116da606083016040840161510d565b6001600160a01b03166116f0602084018461510d565b6001600160a01b03160361171757604051630d11785f60e21b815260040160405180910390fd5b5f611728610440602085018561510d565b90505f61173e610440606086016040870161510d565b90505f61174e602086018661510d565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611789573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117ad9190615593565b90505f6117c0606087016040880161510d565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117fb573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061181f9190615593565b90505f61182f602088018861510d565b6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161185a91906151d4565b602060405180830381865afa158015611875573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611899919061570d565b90505f6118ac6060890160408a0161510d565b6001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016118d791906151d4565b602060405180830381865afa1580156118f2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611916919061570d565b905061194c61192b60808a0160608b0161510d565b60208a0180359061193c908c61510d565b6001600160a01b0316919061384c565b61195c6080890160608a0161510d565b6001600160a01b0316637f0f41d761197760208b018b61510d565b60208b013561198c60608d0160408e0161510d565b61199960808e018e615757565b6040518663ffffffff1660e01b81526004016119b9959493929190615799565b5f604051808303815f87803b1580156119d0575f80fd5b505af11580156119e2573d5f803e3d5ffd5b505050505f818960400160208101906119fb919061510d565b6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401611a2691906151d4565b602060405180830381865afa158015611a41573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a65919061570d565b611a6f919061565c565b90505f611a7f60208b018b61510d565b6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401611aaa91906151d4565b602060405180830381865afa158015611ac5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ae9919061570d565b611af3908561565c565b9050611b0561042160208c018c61510d565b60098a015f611b1760208e018e61510d565b6001600160a01b03166001600160a01b031681526020019081526020015f2054611b41919061565c565b811115611b6157604051630301465d60e11b815260040160405180910390fd5b5f611b6d8389886129f6565b90505f611b7b838b8a6129f6565b90505f611b8b60208e018e61510d565b8d6040016020810190611b9e919061510d565b604051602001611baf9291906157e9565b6040516020818303038152906040528051906020012090506127108c6008015f8381526020019081526020015f2054612710611beb919061565c565b611bf590846155da565b611bff9190615605565b831015611c1e57604051625713a160e91b815260040160405180910390fd5b838c6009015f015f8f5f016020810190611c38919061510d565b6001600160a01b03166001600160a01b031681526020019081526020015f205f828254611c65919061565c565b92505081905550848c6009015f015f8f6040016020810190611c87919061510d565b6001600160a01b03166001600160a01b031681526020019081526020015f205f828254611cb491906155c7565b90915550611cca905060608e0160408f0161510d565b6001600160a01b0316611ce060208f018f61510d565b6040805187815260208101899052908101859052606081018690526001600160a01b0391909116907fb8c3fd52c06cd7e35d81a3fc31542187d197c9deef253587a27e0214677d0f6b9060800160405180910390a350505050505050505050505050565b5f80611d4e61293d565b805460408051635c975abb60e01b815290519293506001600160a01b0390911691635c975abb916004808201926020929091908290030181865afa158015611d98573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dbc9190615724565b15611dda576040516313d0ff5960e31b815260040160405180910390fd5b611de384611e4d565b91505f84611e0b612710611df56138a2565b611e019061271061565c565b8891906001612b1e565b611e15919061565c565b905061156a82868587856136e0565b60605f611e2f612a21565b90508060040180546109c790615624565b5f33610a67818585612d16565b5f80611e73612710611e5d6138a2565b611e699061271061565c565b8591906001612b1e565b9050610d38816138dc565b5f611e87612d97565b5f611e9061293d565b90505f611e9b610bd2565b90505f611ea785612167565b905080871115611ed057848782604051633fa733bb60e21b8152600401610daf939291906156c3565b611ed987610a71565b93505f80611ee98587868a612e3a565b9092509050611f068289611efd848a61565c565b878b8e8c6138e8565b50505050509392505050565b6060611f1c61293d565b600501805480602002602001604051908101604052809291908181526020018280548015611f7157602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311611f53575b5050505050905090565b5f611f84612d97565b5f611f8d61293d565b90505f611f98610bd2565b90505f611fa485612174565b905080871115611fcd57848782604051632e52afbb60e21b8152600401610daf939291906156c3565b611fd687610fd5565b93505f80611fe6858a868a612e3a565b9092509050611f068289611ffa848d61565c565b878b8b8f6138e8565b61200b612b79565b5f61201461293d565b90506127108211156120395760405163aabd5a0960e01b815260040160405180910390fd5b5f848460405160200161204d9291906157e9565b60408051601f1981840301815291815281516020928301205f908152600890940190915290912091909155505050565b612085612b79565b5f61208e61293d565b9050612098610bd2565b5f036120b7576040516348b5002360e01b815260040160405180910390fd5b6120c4600282018561353d565b6120e15760405163081fcdbf60e21b815260040160405180910390fd5b5f83131561211d57826120ff6001600160a01b03861633308461394a565b6121178561210c8361396b565b6009850191906139d7565b506116b1565b5f6121278461580b565b9050612141856121368361396b565b600985019190613a44565b6121556001600160a01b038616848361384c565b5050505050565b5f610a54825f613ab1565b5f610a5461045f836114ba565b5f610a54826114ba565b5f80612188612a21565b6001600160a01b039485165f90815260019190910160209081526040808320959096168252939093525050205490565b5f6121c1612d97565b5f6121ca61293d565b90505f6121d684612167565b9050808811156121ff57838882604051633fa733bb60e21b8152600401610daf939291906156c3565b61220888610a71565b925061221682845f87612e3a565b505061225782898989808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152508b9250612eeb915050565b836001600160a01b0316856001600160a01b0316336001600160a01b03165f80516020615b3a8339815191528b87604051610e4c9291906156e4565b5f61229c61293d565b335f908152600c8201602052604090205490915060ff166122d0576040516358164d9160e11b815260040160405180910390fd5b5f6122da85610ef3565b90505f6122e8610440610e5f565b90505f61236483836122f8610d3f565b8a6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015612334573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123589190615593565b8a939291906001613ae5565b90505f8186111561237c57612379828761565c565b90505b801561239a5761239a8861238f8361396b565b6009880191906139d7565b6123a4818761565c565b6001600160a01b0389165f908152600987016020526040812080549091906123cd9084906155c7565b90915550879050600986015f6123e1610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f205f82825461240e919061565c565b9091555050604080516001600160a01b038a16815260208101899052908101879052606081018290527fc659bef2facfde65b659c8c5160cf21ac8232b38f8331aac0cea195e1d9296659060800160405180910390a15050505050505050565b5f805f61247a846136ba565b9092509050610aa3818361565c565b612491612b79565b5f61249a61293d565b90505f6124a5611f12565b90506124af610e5f565b6001600160a01b0316846001600160a01b0316036124e05760405163d3c4f33360e01b815260040160405180910390fd5b80515f5b8181101561253f57856001600160a01b03168382815181106125085761250861557f565b60200260200101516001600160a01b031603612537576040516360f7af0b60e11b815260040160405180910390fd5b6001016124e4565b5061254d6002840186613b2a565b61256a57604051631cf57a9f60e11b815260040160405180910390fd5b825460408051633a0df78d60e11b815290515f926001600160a01b03169163741bef1a9160048083019260209291908290030181865afa1580156125b0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125d491906156f2565b604051635670bcc760e11b81529091506001600160a01b0382169063ace1798e906126039089906004016151d4565b602060405180830381865afa15801561261e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612642919061570d565b5f036126615760405163fb94c4ed60e01b815260040160405180910390fd5b61266f600985018787612c1e565b7f252fb22f1e5dcdba04908f13259852204aead54fea1342d028eb2f49510bee978660405161269e91906151d4565b60405180910390a1505050505050565b5f6126b7613b3e565b805490915060ff600160401b82041615906001600160401b03165f811580156126dd5750825b90505f826001600160401b031660011480156126f85750303b155b905081158015612706575080155b156127245760405163f92ee8a960e01b815260040160405180910390fd5b84546001600160401b0319166001178555831561274d57845460ff60401b1916600160401b1785555b5f61275661293d565b90505f6127696080890160608a0161510d565b6001600160a01b0316148061279557505f61278a60a0890160808a0161510d565b6001600160a01b0316145b806127b757505f6127ac60c0890160a08a0161510d565b6001600160a01b0316145b156127d557604051639fabe1c160e01b815260040160405180910390fd5b6127e5608088016060890161510d565b81546001600160a01b0319166001600160a01b039190911617815561281060e0880160c0890161510d565b6001820180546001600160a01b0319166001600160a01b039290921691909117905561285b8161284660a08a0160808b0161510d565b61285660c08b0160a08c0161510d565b613766565b6128e561286b6020890189615757565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506128ac9250505060408a018a615757565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250613b6292505050565b6128fa6128f5602089018961510d565b613b74565b508315610bca57845460ff60401b191685556040517fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29061269e90600190615825565b7f3c2bbd5b01c023780ac7877400fd851b17fd98c152afdb1efc02015acd68a30090565b5f610a54825490565b6001600160a01b0381165f9081526001830160209081526040808320815160608101835290546001600160801b03811682526001600160401b03600160801b8204811694830194909452600160c01b9004909216908201526129d4816129cf816132cd565b6132fe565b6001600160a01b0384165f90815260208690526040902054610aa3919061565c565b5f612a0282600a61591c565b612a0c84866155da565b610aa39190615605565b5f610d388383613b85565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0090565b5f610d38612a516107e9565b612a5c9060016155c7565b612a675f600a61591c565b612a6f610bd2565b612a7991906155c7565b85919085612b1e565b610acc8383836001613bab565b5f610a54826001613ab1565b5f80612aa561293d565b80546040516301646b0560e61b81529192506001600160a01b03169063591ac14090612ad59033906004016151d4565b602060405180830381865afa158015612af0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b14919061592a565b61ffff1691505090565b5f80612b2b868686613c7c565b90506001836002811115612b4157612b4161594b565b148015612b5d57505f8480612b5857612b586155f1565b868809115b15612b7057612b6d6001826155c7565b90505b95945050505050565b612b8161293d565b5460408051638da5cb5b60e01b815290516001600160a01b0390921691638da5cb5b916004808201926020929091908290030181865afa158015612bc7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612beb91906156f2565b6001600160a01b0316336001600160a01b031614612c1c57604051635fc483c560e01b815260040160405180910390fd5b565b64e8d4a510006001600160401b0382161115612c4d576040516304bba2fb60e51b815260040160405180910390fd5b612c5883835f613d25565b6001600160a01b0382165f8181526001850160205260409081902080546001600160c01b0316600160c01b6001600160401b03861602179055517f5577d4c8f6e5397effa5c71df8fe221e1162e18aaa0aabe87026cfb0c676215090612cbf908490615825565b60405180910390a2505050565b5f612cd7848461217e565b90505f1981146116b15781811015612d0857828183604051637dc7a0d960e11b8152600401610daf939291906156c3565b6116b184848484035f613bab565b6001600160a01b038316612d3f575f604051634b637e8f60e11b8152600401610daf91906151d4565b6001600160a01b038216612d68575f60405163ec442f0560e01b8152600401610daf91906151d4565b610acc838383613e89565b7f0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e0090565b5f612da061293d565b8054604080516341ba27eb60e01b815290519293506001600160a01b03909116916341ba27eb916004808201926020929091908290030181865afa158015612dea573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e0e919061595f565b6001600160401b0316421015612e375760405163abdc9be160e01b815260040160405180910390fd5b50565b5f80612e4e612e47612a9b565b8690613385565b9050336001600160a01b03841614612e6b57612e6b833387612ccc565b8315612eba57612eb7600987015f612e81610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f2054855f8489612eaf919061565c565b929190612b1e565b91505b8015612ed8576001860154612ed8906001600160a01b031682613fac565b612ee28386613fe0565b94509492505050565b5f612ef583614014565b90508060400151612f0886600201612961565b612f1291906155c7565b612f1d9060016155c7565b815114612f3d57604051634ec4810560e11b815260040160405180910390fd5b335f908152600d8601602052604090205460ff16158015612f9f5750612f61610e5f565b6001600160a01b0316836001835f0151612f7b919061565c565b81518110612f8b57612f8b61557f565b60200260200101516001600160a01b031614155b15612fbd57604051631bad141f60e31b815260040160405180910390fd5b8051612fca9084906140b7565b835f612fd7610440610e5f565b90505f5b835181108015612fea57508215155b15613200575f8682815181106130025761300261557f565b6020026020010151905061304185602001518660400151613021610e5f565b61302e60028e018661353d565b6001600160a01b0386169392919061414d565b5f61304f60098b018361296a565b9050805f0361305f5750506131ee565b5f61306983610ef3565b9050805f0361307a575050506131ee565b5f836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156130b7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130db9190615593565b90505f6130e6610e5f565b6001600160a01b0316856001600160a01b031603613105575086613120565b61311d8388613112610d3f565b8b929190865f613ae5565b90505b80841061315f576001600160a01b0385165f90815260098e0160205260408120805491995082918a9061315490849061565c565b909155506131c59050565b5f61316a858361565c565b90506131838489613179610d3f565b84929190876141db565b9850849150818e6009015f015f886001600160a01b03166001600160a01b031681526020019081526020015f205f8282546131be919061565c565b9091555050505b80896060015187815181106131dc576131dc61557f565b60200260200101818152505050505050505b806131f88161573f565b915050612fdb565b505f5b835181101561328d575f846060015182815181106132235761322361557f565b6020026020010151111561328557613285858560600151838151811061324b5761324b61557f565b60200260200101518884815181106132655761326561557f565b60200260200101516001600160a01b031661384c9092919063ffffffff16565b600101613203565b50836001600160a01b03165f80516020615ba1833981519152878786606001516040516132bc9392919061597a565b60405180910390a250505050505050565b60208101515f906001600160401b03166132f464e8d4a510006132ef85614238565b61426d565b610a5491906155c7565b5f81421061330d57505f610a54565b5f83602001516001600160401b031642613327919061565c565b90505f8161333486614238565b61333e91906155da565b855190915064e8d4a510009061335d906001600160801b0316836155da565b6133679190615605565b855161337c91906001600160801b031661565c565b92505050610a54565b5f610d3883836127106001612b1e565b306001600160a01b037f000000000000000000000000b86ea1873bd4c7dd3525b8ea623516b5cba4eb9216148061341b57507f000000000000000000000000b86ea1873bd4c7dd3525b8ea623516b5cba4eb926001600160a01b031661340f5f80516020615b5a833981519152546001600160a01b031690565b6001600160a01b031614155b15612c1c5760405163703e46dd60e11b815260040160405180910390fd5b612e37612b79565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa92505050801561349b575060408051601f3d908101601f191682019092526134989181019061570d565b60015b6134ba5781604051634c9c8ce360e01b8152600401610daf91906151d4565b5f80516020615b5a83398151915281146134ea57604051632a87526960e21b815260048101829052602401610daf565b610acc838361428f565b306001600160a01b037f000000000000000000000000b86ea1873bd4c7dd3525b8ea623516b5cba4eb921614612c1c5760405163703e46dd60e11b815260040160405180910390fd5b5f610d38836001600160a01b0384166142e4565b5f61355a61293d565b6001600160a01b0385165f908152600782016020526040902054909150156135955760405163caf865c160e01b815260040160405180910390fd5b5f8160050184815481106135ab576135ab61557f565b5f9182526020808320909101546001600160a01b031680835260098501909152604090912054909150158015906135e0575082155b156135fe576040516305ec751560e51b815260040160405180910390fd5b6136098460016155c7565b6001600160a01b0386165f9081526007840160205260409020556005820180548691908690811061363c5761363c61557f565b5f9182526020918290200180546001600160a01b0319166001600160a01b03938416179055604080518484168152928816918301919091527f9e147d339c63698deb55c3d0d44ed3eba29bac2a068a88c4bc5bde17d6331e19910160405180910390a15050505050565b5f610d38836001600160a01b0384166142fb565b5f806136c58361215c565b91506136d96136d26138a2565b8390613385565b9050915091565b6136ea33846143de565b8015613708576001850154613708906001600160a01b031682613fac565b6137128285613fac565b816001600160a01b0316336001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d785876040516137579291906156e4565b60405180910390a35050505050565b6001600160a01b0381165f908152600b8401602052604090205460ff16156137a157604051631f160d3160e11b815260040160405180910390fd5b6001600160a01b0382165f908152600c8401602052604090205460ff16156137dc57604051632748f32960e21b815260040160405180910390fd5b6001600160a01b038181165f818152600b8601602090815260408083208054600160ff199182168117909255958816808552600c8a0190935281842080549096161790945592517fd6c91941062a66dc4c4344f6b10af4b565b256816a2f9080ba7f83e1d6a2bdc69190a3505050565b610acc8363a9059cbb60e01b848460405160240161386b9291906159d4565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614492565b5f806138ac61293d565b8054604051636034d9f560e01b81529192506001600160a01b031690636034d9f590612ad59033906004016151d4565b5f610a54826001612a45565b6138f28787614563565b6138fd86868661460f565b826001600160a01b0316866001600160a01b0316336001600160a01b03165f80516020615b3a83398151915285856040516139399291906156e4565b60405180910390a450505050505050565b6116b1846323b872dd60e01b85858560405160240161386b939291906159ed565b5f6001600160801b038211156139d35760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b6064820152608401610daf565b5090565b806001600160801b03165f03613a005760405163d11b25af60e01b815260040160405180910390fd5b613a0b838383613d25565b816001600160a01b03167f693ffe037fd29f4846b006bd3ada57d4fd4c3622277227342f0e4fed9011dc2082604051612cbf919061541a565b806001600160801b03165f03613a6d5760405163d11b25af60e01b815260040160405180910390fd5b613a78838383614995565b816001600160a01b03167f5f4e7177e0f8e013ddb6d29e468fa7a45f8df4e00e7895b7f20c5979cab21c6c82604051612cbf919061541a565b5f610d38613ac082600a61591c565b613ac8610bd2565b613ad291906155c7565b613ada6107e9565b612a799060016155c7565b5f80613aff86613af687600a61591c565b8a919086612b1e565b90508615613b1b57613b1381888686614a73565b915050613b20565b5f9150505b9695505050505050565b5f610d38836001600160a01b038416614aa2565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0090565b613b6a614ae9565b6110138282614b0e565b613b7c614ae9565b612e3781614b3e565b5f825f018281548110613b9a57613b9a61557f565b905f5260205f200154905092915050565b5f613bb4612a21565b90506001600160a01b038516613bdf575f60405163e602df0560e01b8152600401610daf91906151d4565b6001600160a01b038416613c08575f604051634a1406b160e11b8152600401610daf91906151d4565b6001600160a01b038086165f9081526001830160209081526040808320938816835292905220839055811561215557836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258560405161375791815260200190565b5f80805f19858709858702925082811083820303915050805f03613cb357838281613ca957613ca96155f1565b0492505050610d38565b808411613cbe575f80fd5b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b6001600160a01b0382165f9081526001840160209081526040808320815160608101835290546001600160801b03811682526001600160401b03600160801b8204811694830194909452600160c01b90049092169082015290613d87826132cd565b90505f613db0846001600160801b0316613da185856132fe565b613dab91906155c7565b61396b565b6001600160801b03811684529050613dc742614bab565b6001600160401b03166020808501919091526001600160a01b0386165f908152908790526040812080546001600160801b0387169290613e089084906155c7565b909155505050506001600160a01b03929092165f9081526001939093016020908152604093849020835181549285015194909501516001600160801b039095166001600160c01b031990921691909117600160801b6001600160401b0394851602176001600160c01b0316600160c01b939094169290920292909217905550565b5f613e92612a21565b90506001600160a01b038416613ec05781816002015f828254613eb591906155c7565b90915550613f1d9050565b6001600160a01b0384165f9081526020829052604090205482811015613eff5784818460405163391434e360e21b8152600401610daf939291906156c3565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b038316613f3b576002810180548390039055613f59565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051613f9e91815260200190565b60405180910390a350505050565b6001600160a01b038216613fd5575f60405163ec442f0560e01b8152600401610daf91906151d4565b6110135f8383613e89565b6001600160a01b038216614009575f604051634b637e8f60e11b8152600401610daf91906151d4565b611013825f83613e89565b61403d60405180608001604052805f8152602001606081526020015f8152602001606081525090565b5f614046611f12565b90505f83519050604051806080016040528082815260200183815260200183518152602001826001600160401b03811115614083576140836151e8565b6040519080825280602002602001820160405280156140ac578160200160208202803683370190505b509052949350505050565b5f5b81811015610acc575f6140cd8260016155c7565b90505b82811015614144578381815181106140ea576140ea61557f565b60200260200101516001600160a01b031684838151811061410d5761410d61557f565b60200260200101516001600160a01b03160361413c576040516323271fb560e11b815260040160405180910390fd5b6001016140d0565b506001016140b9565b808061416a5750816001600160a01b0316856001600160a01b0316145b612155575f805b848110156141bc57866001600160a01b03168682815181106141955761419561557f565b60200260200101516001600160a01b0316036141b457600191506141bc565b600101614171565b5080610bca5760405163c1ab6dc160e01b815260040160405180910390fd5b5f806141e883600a61591c565b6141f287896155da565b6141fc9190615605565b9050841561422c578461421085600a61591c565b61421a90836155da565b6142249190615605565b915050612b70565b505f9695505050505050565b5f81604001516001600160401b03165f1461425757816040015161425e565b64174876e8005b6001600160401b031692915050565b5f81600161427b82866155c7565b614285919061565c565b610d389190615605565b61429882614c12565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156142dc57610acc8282614c6c565b611013614c91565b5f9081526001919091016020526040902054151590565b5f81815260018301602052604081205480156143d5575f61431d60018361565c565b85549091505f906143309060019061565c565b905081811461438f575f865f01828154811061434e5761434e61557f565b905f5260205f200154905080875f01848154811061436e5761436e61557f565b5f918252602080832090910192909255918252600188019052604090208390555b85548690806143a0576143a0615a11565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610a54565b5f915050610a54565b5f6143e761293d565b90506143f1610e5f565b6001600160a01b031663e75b3ae784846040518363ffffffff1660e01b815260040161441e9291906159d4565b5f604051808303815f87803b158015614435575f80fd5b505af1158015614447573d5f803e3d5ffd5b5050505081816009015f015f61445b610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f205f82825461448891906155c7565b9091555050505050565b5f6144e6826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614cb09092919063ffffffff16565b805190915015610acc57808060200190518101906145049190615724565b610acc5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610daf565b5f61456c61293d565b9050614576610e5f565b6001600160a01b03166320c582be3084866040518463ffffffff1660e01b81526004016145a5939291906159ed565b5f604051808303815f87803b1580156145bc575f80fd5b505af11580156145ce573d5f803e3d5ffd5b5050505082816009015f015f6145e2610e5f565b6001600160a01b03166001600160a01b031681526020019081526020015f205f828254614488919061565c565b5f61461861293d565b90505f614623611f12565b80519091505f61463560028501612961565b90505f61464282846155c7565b6001600160401b03811115614659576146596151e8565b604051908082528060200260200182016040528015614682578160200160208202803683370190505b5090505f61469083856155c7565b6001600160401b038111156146a7576146a76151e8565b6040519080825280602002602001820160405280156146d0578160200160208202803683370190505b5090505f5b848110156147fb575f61470d8783815181106146f3576146f361557f565b60200260200101518960090161296a90919063ffffffff16565b905061471b8a828b5f612b1e565b84838151811061472d5761472d61557f565b60200260200101818152505086828151811061474b5761474b61557f565b60200260200101518383815181106147655761476561557f565b60200260200101906001600160a01b031690816001600160a01b0316815250508382815181106147975761479761557f565b6020026020010151886009015f015f8985815181106147b8576147b861557f565b60200260200101516001600160a01b03166001600160a01b031681526020019081526020015f205f8282546147ed919061565c565b9091555050506001016146d5565b505f5b838110156148f3575f61481186836155c7565b90505f61482160028a0184612a16565b90505f61483160098b018361296a565b905061483f8c828d5f612b1e565b8684815181106148515761485161557f565b602002602001018181525050818584815181106148705761487061557f565b60200260200101906001600160a01b031690816001600160a01b0316815250508583815181106148a2576148a261557f565b60200260200101518a6009015f015f846001600160a01b03166001600160a01b031681526020019081526020015f205f8282546148df919061565c565b9091555050600190930192506147fe915050565b505f5b8151811015614957578281815181106149115761491161557f565b60200260200101515f1461494f5761494f8a8483815181106149355761493561557f565b60200260200101518484815181106132655761326561557f565b6001016148f6565b50886001600160a01b03165f80516020615ba18339815191528983856040516149829392919061597a565b60405180910390a2505050505050505050565b6001600160a01b0382165f9081526001840160209081526040808320815160608101835290546001600160801b03811682526001600160401b03600160801b8204811694830194909452600160c01b900490921690820152906149f7826132cd565b90505f614a1b846001600160801b0316614a1185856132fe565b613dab919061565c565b6001600160801b03811684529050614a3242614bab565b6001600160401b03166020808501919091526001600160a01b0386165f908152908790526040812080546001600160801b0387169290613e0890849061565c565b5f831580614a7f575084155b15614a8b57505f610aa3565b612b70614a9984600a61591c565b86908685612b1e565b5f614aad83836142e4565b614ae257508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610a54565b505f610a54565b614af1614cbe565b612c1c57604051631afcd79f60e31b815260040160405180910390fd5b614b16614ae9565b5f614b1f612a21565b905060038101614b2f8482615a69565b50600481016116b18382615a69565b614b46614ae9565b5f614b4f612d73565b90505f80614b5c84614cd7565b9150915081614b6c576012614b6e565b805b83546001600160a81b031916600160a01b60ff92909216919091026001600160a01b031916176001600160a01b0394909416939093179091555050565b5f6001600160401b038211156139d35760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660448201526534206269747360d01b6064820152608401610daf565b806001600160a01b03163b5f03614c3e5780604051634c9c8ce360e01b8152600401610daf91906151d4565b5f80516020615b5a83398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b6060610d388383604051806060016040528060278152602001615b7a60279139614dad565b3415612c1c5760405163b398979f60e01b815260040160405180910390fd5b6060610aa384845f85614e17565b5f614cc7613b3e565b54600160401b900460ff16919050565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290515f918291829182916001600160a01b03871691614d1d91615b23565b5f60405180830381855afa9150503d805f8114614d55576040519150601f19603f3d011682016040523d82523d5f602084013e614d5a565b606091505b5091509150818015614d6e57506020815110155b15614da1575f81806020019051810190614d88919061570d565b905060ff8111614d9f576001969095509350505050565b505b505f9485945092505050565b60605f80856001600160a01b031685604051614dc99190615b23565b5f60405180830381855af49150503d805f8114614e01576040519150601f19603f3d011682016040523d82523d5f602084013e614e06565b606091505b5091509150613b2086838387614eee565b606082471015614e785760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610daf565b5f80866001600160a01b03168587604051614e939190615b23565b5f6040518083038185875af1925050503d805f8114614ecd576040519150601f19603f3d011682016040523d82523d5f602084013e614ed2565b606091505b5091509150614ee387838387614eee565b979650505050505050565b60608315614f5c5782515f03614f55576001600160a01b0385163b614f555760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610daf565b5081610aa3565b610aa38383815115614f715781518083602001fd5b8060405162461bcd60e51b8152600401610daf91905b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b5f60208284031215614fcc575f80fd5b5035919050565b6001600160a01b0381168114612e37575f80fd5b5f8060408385031215614ff8575f80fd5b823561500381614fd3565b946020939093013593505050565b6001600160401b0381168114612e37575f80fd5b5f8060408385031215615036575f80fd5b823561504181614fd3565b9150602083013561505181615011565b809150509250929050565b5f8083601f84011261506c575f80fd5b5081356001600160401b03811115615082575f80fd5b6020830191508360208260051b850101111561509c575f80fd5b9250929050565b5f805f80604085870312156150b6575f80fd5b84356001600160401b038111156150cb575f80fd5b6150d78782880161505c565b90955093505060208501356001600160401b038111156150f5575f80fd5b6151018782880161505c565b95989497509550505050565b5f6020828403121561511d575f80fd5b8135610d3881614fd3565b5f805f6060848603121561513a575f80fd5b833561514581614fd3565b9250602084013561515581614fd3565b929592945050506040919091013590565b5f805f805f6080868803121561517a575f80fd5b8535945060208601356001600160401b03811115615196575f80fd5b6151a28882890161505c565b90955093505060408601356151b681614fd3565b915060608601356151c681614fd3565b809150509295509295909350565b6001600160a01b0391909116815260200190565b634e487b7160e01b5f52604160045260245ffd5b5f806040838503121561520d575f80fd5b823561521881614fd3565b915060208301356001600160401b03811115615232575f80fd5b8301601f81018513615242575f80fd5b80356001600160401b0381111561525b5761525b6151e8565b604051601f8201601f19908116603f011681016001600160401b0381118282101715615289576152896151e8565b6040528181528282016020018710156152a0575f80fd5b816020840160208301375f602083830101528093505050509250929050565b8015158114612e37575f80fd5b5f805f606084860312156152de575f80fd5b83356152e981614fd3565b925060208401356152f981615011565b91506040840135615309816152bf565b809150509250925092565b5f8060408385031215615325575f80fd5b82359150602083013561505181614fd3565b5f8060208385031215615348575f80fd5b82356001600160401b0381111561535d575f80fd5b6153698582860161505c565b90969095509350505050565b602080825282518282018190525f918401906040840190835b818110156153ac57835183526020938401939092019160010161538e565b509095945050505050565b5f805f606084860312156153c9575f80fd5b83356153d481614fd3565b925060208401356152f981614fd3565b5f602082840312156153f4575f80fd5b81356001600160401b03811115615409575f80fd5b820160a08185031215610d38575f80fd5b6001600160801b0391909116815260200190565b5f805f60608486031215615440575f80fd5b83359250602084013561545281614fd3565b9150604084013561530981614fd3565b5f8151808452602084019350602083015f5b8281101561549b5781516001600160a01b0316865260209586019590910190600101615474565b5093949350505050565b602081525f610d386020830184615462565b5f805f606084860312156154c9575f80fd5b83356154d481614fd3565b925060208401359150604084013561530981614fd3565b5f80604083850312156154fc575f80fd5b823561550781614fd3565b9150602083013561505181614fd3565b5f805f60608486031215615529575f80fd5b833561553481614fd3565b95602085013595506040909401359392505050565b5f60208284031215615559575f80fd5b81356001600160401b0381111561556e575f80fd5b820160e08185031215610d38575f80fd5b634e487b7160e01b5f52603260045260245ffd5b5f602082840312156155a3575f80fd5b815160ff81168114610d38575f80fd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115610a5457610a546155b3565b8082028115828204841417610a5457610a546155b3565b634e487b7160e01b5f52601260045260245ffd5b5f8261561f57634e487b7160e01b5f52601260045260245ffd5b500490565b600181811c9082168061563857607f821691505b60208210810361565657634e487b7160e01b5f52602260045260245ffd5b50919050565b81810381811115610a5457610a546155b3565b5f6020828403121561567f575f80fd5b8135610d38816152bf565b5f61ffff821661ffff81036156a1576156a16155b3565b60010192915050565b60ff8181168382160190811115610a5457610a546155b3565b6001600160a01b039390931683526020830191909152604082015260600190565b918252602082015260400190565b5f60208284031215615702575f80fd5b8151610d3881614fd3565b5f6020828403121561571d575f80fd5b5051919050565b5f60208284031215615734575f80fd5b8151610d38816152bf565b5f60018201615750576157506155b3565b5060010190565b5f808335601e1984360301811261576c575f80fd5b8301803591506001600160401b03821115615785575f80fd5b60200191503681900382131561509c575f80fd5b6001600160a01b03868116825260208201869052841660408201526080606082018190528101829052818360a08301375f81830160a090810191909152601f909201601f19160101949350505050565b6001600160601b0319606093841b811682529190921b16601482015260280190565b5f600160ff1b820161581f5761581f6155b3565b505f0390565b6001600160401b0391909116815260200190565b6001815b600184111561587457808504811115615858576158586155b3565b600184161561586657908102905b60019390931c92800261583d565b935093915050565b5f8261588a57506001610a54565b8161589657505f610a54565b81600181146158ac57600281146158b6576158d2565b6001915050610a54565b60ff8411156158c7576158c76155b3565b50506001821b610a54565b5060208310610133831016604e8410600b84101617156158f5575081810a610a54565b6159015f198484615839565b805f1904821115615914576159146155b3565b029392505050565b5f610d3860ff84168361587c565b5f6020828403121561593a575f80fd5b815161ffff81168114610d38575f80fd5b634e487b7160e01b5f52602160045260245ffd5b5f6020828403121561596f575f80fd5b8151610d3881615011565b838152606060208201525f6159926060830185615462565b8281036040840152835180825260208086019201905f5b818110156159c75783518352602093840193909201916001016159a9565b5090979650505050505050565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b5f52603160045260245ffd5b601f821115610acc57805f5260205f20601f840160051c81016020851015615a4a5750805b601f840160051c820191505b81811015612155575f8155600101615a56565b81516001600160401b03811115615a8257615a826151e8565b615a9681615a908454615624565b84615a25565b6020601f821160018114615ac8575f8315615ab15750848201515b5f19600385901b1c1916600184901b178455612155565b5f84815260208120601f198516915b82811015615af75787850151825560209485019460019092019101615ad7565b5084821015615b1457868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b5f82518060208501845e5f92019182525091905056fefbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c656486bcb277da75a9fbb738b8bb82beb731d82a0a89516b848730df92849f966bf0a2646970667358221220958dddfaf5841522c4d7d2b3154be2f884ebbf892ce000a781919beaf686978e64736f6c634300081a0033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 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.