// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @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
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [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.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable 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._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
(bool success, bytesmemory 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._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
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._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory 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._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory 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._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
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 contractrequire(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._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 40: ArrayExtensions.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;libraryArrayExtensions{
functioncopy(uint256[] memory array) internalpurereturns (uint256[] memory) {
uint256[] memory copy_ =newuint256[](array.length);
for (uint256 i =0; i < array.length; i++) {
copy_[i] = array[i];
}
return copy_;
}
functionconcat(address[] memory a,
address[] memory b
) internalpurereturns (address[] memory result) {
result =newaddress[](a.length+ b.length);
for (uint256 i; i < a.length; i++) result[i] = a[i];
for (uint256 i; i < b.length; i++) result[i + a.length] = b[i];
}
functionincludes(address[] memory array, address element) internalpurereturns (bool) {
return _includes(array, element, array.length);
}
function_includes(address[] memory array,
address element,
uint256 until
) internalpurereturns (bool) {
for (uint256 i; i < until; i++) {
if (array[i] == element) returntrue;
}
returnfalse;
}
functionremoveDuplicates(address[] memory array) internalpurereturns (address[] memory) {
address[] memory unique =newaddress[](array.length);
uint256 j;
for (uint256 i; i < array.length; i++) {
if (!_includes(unique, array[i], j)) {
unique[j++] = array[i];
}
}
return trim(unique, j);
}
functiontrim(address[] memory array,
uint256 length
) internalpurereturns (address[] memory trimmed) {
trimmed =newaddress[](length);
for (uint256 i; i < length; i++) trimmed[i] = array[i];
}
}
Contract Source Code
File 3 of 40: BaseConicPool.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;import"Ownable.sol";
import"ERC20.sol";
import"Address.sol";
import"EnumerableSet.sol";
import"EnumerableMap.sol";
import"IERC20.sol";
import"SafeERC20.sol";
import"IERC20Metadata.sol";
import"ERC165Checker.sol";
import"IConicPool.sol";
import"IRewardManager.sol";
import"IWithdrawalProcessor.sol";
import"ICurveRegistryCache.sol";
import"IInflationManager.sol";
import"ILpTokenStaker.sol";
import"IOracle.sol";
import"IBaseRewardPool.sol";
import"LpToken.sol";
import"Pausable.sol";
import"ConicPoolWeightManager.sol";
import"ScaledMath.sol";
import"ArrayExtensions.sol";
abstractcontractBaseConicPoolisIConicPool, Pausable{
usingArrayExtensionsforuint256[];
usingArrayExtensionsforaddress[];
usingEnumerableSetforEnumerableSet.AddressSet;
usingEnumerableMapforEnumerableMap.AddressToUintMap;
usingSafeERC20forIERC20;
usingSafeERC20forIERC20Metadata;
usingSafeERC20forILpToken;
usingScaledMathforuint256;
usingAddressforaddress;
usingERC165Checkerforaddress;
// Avoid stack depth errorsstructDepositVars {
uint256 exchangeRate;
uint256 underlyingBalanceIncrease;
uint256 mintableUnderlyingAmount;
uint256 lpReceived;
uint256 underlyingBalanceBefore;
uint256 allocatedBalanceBefore;
uint256[] allocatedPerPoolBefore;
uint256 underlyingBalanceAfter;
uint256 allocatedBalanceAfter;
uint256[] allocatedPerPoolAfter;
}
uint256internalconstant _IDLE_RATIO_UPPER_BOUND =0.2e18;
uint256internalconstant _MIN_DEPEG_THRESHOLD =0.01e18;
uint256internalconstant _MAX_DEPEG_THRESHOLD =0.1e18;
uint256internalconstant _MAX_DEVIATION_UPPER_BOUND =0.2e18;
uint256internalconstant _TOTAL_UNDERLYING_CACHE_EXPIRY =3days;
uint256internalconstant _MAX_USD_VALUE_FOR_REMOVING_POOL =100e18;
uint256internalconstant _MIN_EMERGENCY_REBALANCING_REWARD_FACTOR =1e18;
uint256internalconstant _MAX_EMERGENCY_REBALANCING_REWARD_FACTOR =100e18;
IERC20 internalimmutable CVX;
IERC20 internalimmutable CRV;
IERC20 internalconstant CNC = IERC20(0x9aE380F0272E2162340a5bB646c354271c0F5cFC);
addressinternalconstant _WETH_ADDRESS =0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IERC20Metadata publicimmutableoverride underlying;
ILpToken publicimmutableoverride lpToken;
IRewardManager publicimmutable rewardManager;
IConicPoolWeightManager publicimmutable weightManager;
/// @dev once the deviation gets under this threshold, the reward distribution will be paused/// until the next rebalancing. This is expressed as a ratio, scaled with 18 decimalsuint256public maxDeviation =0.02e18; // 2%uint256public maxIdleCurveLpRatio =0.05e18; // triggers Convex staking when exceededboolpublic isShutdown;
uint256public depegThreshold =0.03e18; // 3%uint256internal _cacheUpdatedTimestamp;
uint256internal _cachedTotalUnderlying;
/// @dev `true` if the rebalancing rewards are enabled, i.e. can become active/// A pool starts rebalancing rewards disabled, and these need to be enabled through governanceboolpublic rebalancingRewardsEnabled;
/// @dev `true` while the reward distribution is activeboolpublic rebalancingRewardActive;
/// @notice the time at which rebalancing rewards have been activateduint64public rebalancingRewardsActivatedAt;
/// @notice The factor by which the rebalancing reward is multiplied when a pool is depeggeduint256public emergencyRebalancingRewardsFactor =10e18;
/// @notice The factor by which the rebalancing reward is multiplied/// this is 1 (scaled to 18 decimals) for normal rebalancing situations but is set/// to `emergencyRebalancingRewardsFactor` when a pool is depeggeduint256public rebalancingRewardsFactor;
/// @dev the absolute value in terms of USD of the total deviation after/// the weights have been updateduint256public totalDeviationAfterWeightUpdate;
mapping(address=>uint256) _cachedPrices;
modifieronlyController() {
require(msg.sender==address(controller), "not authorized");
_;
}
constructor(address _underlying,
IRewardManager _rewardManager,
address _controller,
stringmemory _lpTokenName,
stringmemory _symbol,
address _cvx,
address _crv
) Pausable(IController(_controller)) {
require(
_underlying != _cvx && _underlying != _crv && _underlying !=address(CNC),
"invalid underlying"
);
underlying = IERC20Metadata(_underlying);
uint8 decimals = IERC20Metadata(_underlying).decimals();
lpToken =new LpToken(_controller, address(this), decimals, _lpTokenName, _symbol);
rewardManager = _rewardManager;
weightManager =new ConicPoolWeightManager(
IController(_controller),
IERC20Metadata(_underlying)
);
CVX = IERC20(_cvx);
CRV = IERC20(_crv);
CVX.safeApprove(address(_rewardManager), type(uint256).max);
CRV.safeApprove(address(_rewardManager), type(uint256).max);
CNC.safeApprove(address(_rewardManager), type(uint256).max);
}
/// @dev We always delegate-call to the Curve handler, which means/// that we need to be able to receive the ETH to unwrap it and/// send it to the Curve pool, as well as to receive it back from/// the Curve pool when withdrawingreceive() externalpayable{
require(address(underlying) == _WETH_ADDRESS, "not WETH pool");
}
/// @notice Deposit underlying on behalf of someone/// @param underlyingAmount Amount of underlying to deposit/// @param minLpReceived The minimum amount of LP to accept from the deposit/// @return lpReceived The amount of LP receivedfunctiondepositFor(address account,
uint256 underlyingAmount,
uint256 minLpReceived,
bool stake
) publicoverridenotPausedreturns (uint256) {
runSanityChecks();
DepositVars memory vars;
// Preparing depositrequire(!isShutdown, "pool is shut down");
require(underlyingAmount >0, "deposit amount cannot be zero");
_updateAdapterCachedPrices();
uint256 underlyingPrice_ = controller.priceOracle().getUSDPrice(address(underlying));
// We use the cached price of LP tokens, which is effectively the latest price// because we just updated the cache
(
vars.underlyingBalanceBefore,
vars.allocatedBalanceBefore,
vars.allocatedPerPoolBefore
) = _getTotalAndPerPoolUnderlying(underlyingPrice_, IPoolAdapter.PriceMode.Cached);
vars.exchangeRate = _exchangeRate(vars.underlyingBalanceBefore);
// Executing deposit
underlying.safeTransferFrom(msg.sender, address(this), underlyingAmount);
_depositToCurve(
vars.allocatedBalanceBefore,
vars.allocatedPerPoolBefore,
underlying.balanceOf(address(this))
);
// Minting LP Tokens// We use the minimum between the price of the LP tokens before and after deposit
(
vars.underlyingBalanceAfter,
vars.allocatedBalanceAfter,
vars.allocatedPerPoolAfter
) = _getTotalAndPerPoolUnderlying(underlyingPrice_, IPoolAdapter.PriceMode.Minimum);
vars.underlyingBalanceIncrease = vars.underlyingBalanceAfter - vars.underlyingBalanceBefore;
vars.mintableUnderlyingAmount = _min(underlyingAmount, vars.underlyingBalanceIncrease);
vars.lpReceived = vars.mintableUnderlyingAmount.divDown(vars.exchangeRate);
require(vars.lpReceived >= minLpReceived, "too much slippage");
_cachedTotalUnderlying = vars.underlyingBalanceAfter;
_cacheUpdatedTimestamp =block.timestamp;
if (stake) {
lpToken.mint(address(this), vars.lpReceived, account);
ILpTokenStaker lpTokenStaker = controller.lpTokenStaker();
lpToken.forceApprove(address(lpTokenStaker), vars.lpReceived);
lpTokenStaker.stakeFor(vars.lpReceived, address(this), account);
} else {
lpToken.mint(account, vars.lpReceived, account);
}
_handleRebalancingRewards(
account,
vars.allocatedBalanceBefore,
vars.allocatedPerPoolBefore,
vars.allocatedBalanceAfter,
vars.allocatedPerPoolAfter
);
emit Deposit(msg.sender, account, underlyingAmount, vars.lpReceived);
return vars.lpReceived;
}
/// @notice Deposit underlying/// @param underlyingAmount Amount of underlying to deposit/// @param minLpReceived The minimum amoun of LP to accept from the deposit/// @return lpReceived The amount of LP receivedfunctiondeposit(uint256 underlyingAmount,
uint256 minLpReceived
) externaloverridereturns (uint256) {
return depositFor(msg.sender, underlyingAmount, minLpReceived, true);
}
/// @notice Deposit underlying/// @param underlyingAmount Amount of underlying to deposit/// @param minLpReceived The minimum amoun of LP to accept from the deposit/// @param stake Whether or not to stake in the LpTokenStaker/// @return lpReceived The amount of LP receivedfunctiondeposit(uint256 underlyingAmount,
uint256 minLpReceived,
bool stake
) externaloverridereturns (uint256) {
return depositFor(msg.sender, underlyingAmount, minLpReceived, stake);
}
function_depositToCurve(uint256 totalUnderlying_,
uint256[] memory allocatedPerPool,
uint256 underlyingAmount_
) internal{
uint256 depositsRemaining_ = underlyingAmount_;
uint256 totalAfterDeposit_ = totalUnderlying_ + underlyingAmount_;
// NOTE: avoid modifying `allocatedPerPool`uint256[] memory allocatedPerPoolCopy = allocatedPerPool.copy();
while (depositsRemaining_ >0) {
(uint256 poolIndex_, uint256 maxDeposit_) = weightManager.getDepositPool(
totalAfterDeposit_,
allocatedPerPoolCopy,
_getMaxDeviation()
);
// account for rounding errorsif (depositsRemaining_ < maxDeposit_ +1e2) {
maxDeposit_ = depositsRemaining_;
}
address pool_ = weightManager.getPoolAtIndex(poolIndex_);
// Depositing into least balanced pooluint256 toDeposit_ = _min(depositsRemaining_, maxDeposit_);
address poolAdapter =address(controller.poolAdapterFor(pool_));
poolAdapter.functionDelegateCall(
abi.encodeWithSignature(
"deposit(address,address,uint256)",
pool_,
address(underlying),
toDeposit_
)
);
depositsRemaining_ -= toDeposit_;
allocatedPerPoolCopy[poolIndex_] += toDeposit_;
}
}
/// @notice Get current underlying balance of poolfunctiontotalUnderlying() publicviewvirtualreturns (uint256) {
(uint256 totalUnderlying_, , ) = getTotalAndPerPoolUnderlying();
return totalUnderlying_;
}
functionupdateRewardSpendingApproval(address token, bool approved) external{
require(msg.sender==address(rewardManager), "not authorized");
uint256 amount = approved ? type(uint256).max : 0;
IERC20(token).safeApprove(address(rewardManager), amount);
}
function_exchangeRate(uint256 totalUnderlying_) internalviewreturns (uint256) {
uint256 lpSupply = lpToken.totalSupply();
if (lpSupply ==0|| totalUnderlying_ ==0) return ScaledMath.ONE;
return totalUnderlying_.divDown(lpSupply);
}
/// @notice Get current exchange rate for the pool's LP token to the underlyingfunctionexchangeRate() publicviewvirtualoverridereturns (uint256) {
return _exchangeRate(totalUnderlying());
}
/// @notice Get current exchange rate for the pool's LP token to USD/// @dev This is using the cached total underlying value, so is not precisely accurate.functionusdExchangeRate() externalviewvirtualoverridereturns (uint256) {
uint256 underlyingPrice = controller.priceOracle().getUSDPrice(address(underlying));
return _exchangeRate(cachedTotalUnderlying()).mulDown(underlyingPrice);
}
/// @notice Unstake LP Tokens and withdraw underlying/// @param conicLpAmount Amount of LP tokens to burn/// @param minUnderlyingReceived Minimum amount of underlying to redeem/// This should always be set to a reasonable value (e.g. 2%), otherwise/// the user withdrawing could be forced into paying a withdrawal penalty fee/// by another user/// @return uint256 Total underlying withdrawnfunctionunstakeAndWithdraw(uint256 conicLpAmount,
uint256 minUnderlyingReceived,
address to
) publicoverridereturns (uint256) {
controller.lpTokenStaker().unstakeFrom(conicLpAmount, msg.sender);
return withdraw(conicLpAmount, minUnderlyingReceived, to);
}
functionunstakeAndWithdraw(uint256 conicLpAmount,
uint256 minUnderlyingReceived
) externalreturns (uint256) {
return unstakeAndWithdraw(conicLpAmount, minUnderlyingReceived, msg.sender);
}
functionwithdraw(uint256 conicLpAmount,
uint256 minUnderlyingReceived
) publicoverridereturns (uint256) {
return withdraw(conicLpAmount, minUnderlyingReceived, msg.sender);
}
/// @notice Withdraw underlying/// @param conicLpAmount Amount of LP tokens to burn/// @param minUnderlyingReceived Minimum amount of underlying to redeem/// This should always be set to a reasonable value (e.g. 2%), otherwise/// the user withdrawing could be forced into paying a withdrawal penalty fee/// by another user/// @return uint256 Total underlying withdrawnfunctionwithdraw(uint256 conicLpAmount,
uint256 minUnderlyingReceived,
address to
) publicoverridereturns (uint256) {
runSanityChecks();
// Preparing Withdrawalsrequire(lpToken.balanceOf(msg.sender) >= conicLpAmount, "insufficient balance");
uint256 underlyingBalanceBefore_ = underlying.balanceOf(address(this));
// Processing Withdrawals
(
uint256 totalUnderlying_,
uint256 allocatedUnderlying_,
uint256[] memory allocatedPerPool
) = getTotalAndPerPoolUnderlying();
uint256 underlyingToReceive_ = conicLpAmount.mulDown(_exchangeRate(totalUnderlying_));
{
if (underlyingBalanceBefore_ < underlyingToReceive_) {
uint256 underlyingToWithdraw_ = underlyingToReceive_ - underlyingBalanceBefore_;
_withdrawFromCurve(allocatedUnderlying_, allocatedPerPool, underlyingToWithdraw_);
}
}
// Sending Underlying and burning LP Tokensuint256 underlyingWithdrawn_ = _min(
underlying.balanceOf(address(this)),
underlyingToReceive_
);
require(underlyingWithdrawn_ >= minUnderlyingReceived, "too much slippage");
lpToken.burn(msg.sender, conicLpAmount, msg.sender);
underlying.safeTransfer(to, underlyingWithdrawn_);
_cachedTotalUnderlying = totalUnderlying_ - underlyingWithdrawn_;
_cacheUpdatedTimestamp =block.timestamp;
// state has already been updated, so no need to worry about re-entrancyif (to.supportsInterface(type(IWithdrawalProcessor).interfaceId)) {
IWithdrawalProcessor(to).processWithdrawal(msg.sender, underlyingWithdrawn_);
}
emit Withdraw(msg.sender, underlyingWithdrawn_);
return underlyingWithdrawn_;
}
function_withdrawFromCurve(uint256 totalUnderlying_,
uint256[] memory allocatedPerPool,
uint256 amount_
) internal{
uint256 withdrawalsRemaining_ = amount_;
uint256 totalAfterWithdrawal_ = totalUnderlying_ - amount_;
// NOTE: avoid modifying `allocatedPerPool`uint256[] memory allocatedPerPoolCopy = allocatedPerPool.copy();
while (withdrawalsRemaining_ >0) {
(uint256 poolIndex_, uint256 maxWithdrawal_) = weightManager.getWithdrawPool(
totalAfterWithdrawal_,
allocatedPerPoolCopy,
_getMaxDeviation()
);
address pool_ = weightManager.getPoolAtIndex(poolIndex_);
// Withdrawing from least balanced pooluint256 toWithdraw_ = _min(withdrawalsRemaining_, maxWithdrawal_);
address poolAdapter =address(controller.poolAdapterFor(pool_));
poolAdapter.functionDelegateCall(
abi.encodeWithSignature(
"withdraw(address,address,uint256)",
pool_,
underlying,
toWithdraw_
)
);
withdrawalsRemaining_ -= toWithdraw_;
allocatedPerPoolCopy[poolIndex_] -= toWithdraw_;
}
}
functionallPools() externalviewoverridereturns (address[] memory) {
return weightManager.allPools();
}
functionpoolsCount() externalviewoverridereturns (uint256) {
return weightManager.poolsCount();
}
functiongetPoolAtIndex(uint256 _index) externalviewoverridereturns (address) {
return weightManager.getPoolAtIndex(_index);
}
functionisRegisteredPool(address _pool) externalviewreturns (bool) {
return weightManager.isRegisteredPool(_pool);
}
// Controller and Admin functionsfunctionaddPool(address _pool) externaloverrideonlyOwner{
weightManager.addPool(_pool);
address booster = controller.convexBooster();
address lpToken_ = controller.poolAdapterFor(_pool).lpToken(_pool);
IERC20(lpToken_).safeApprove(booster, type(uint256).max);
}
functionremovePool(address _pool) externaloverrideonlyOwner{
weightManager.removePool(_pool);
address booster = controller.convexBooster();
address lpToken_ = controller.poolAdapterFor(_pool).lpToken(_pool);
IERC20(lpToken_).safeApprove(booster, 0);
}
functionupdateWeights(PoolWeight[] memory poolWeights) externalonlyController{
runSanityChecks();
weightManager.updateWeights(poolWeights);
(
uint256 totalUnderlying_,
uint256 totalAllocated,
uint256[] memory allocatedPerPool
) = getTotalAndPerPoolUnderlying();
uint256 totalDeviation = weightManager.computeTotalDeviation(
totalUnderlying_,
allocatedPerPool
);
totalDeviationAfterWeightUpdate = totalDeviation;
rebalancingRewardActive =
rebalancingRewardsEnabled &&!_isBalanced(allocatedPerPool, totalAllocated);
rebalancingRewardsFactor = ScaledMath.ONE;
rebalancingRewardsActivatedAt =uint64(block.timestamp);
// Updating price cache for all pools// Used for seeing if a pool has depegged
_updatePriceCache();
}
functionshutdownPool() externaloverrideonlyController{
require(!isShutdown, "pool already shut down");
isShutdown =true;
emit Shutdown();
}
functionupdateDepegThreshold(uint256 newDepegThreshold_) externalonlyOwner{
require(newDepegThreshold_ >= _MIN_DEPEG_THRESHOLD, "invalid depeg threshold");
require(newDepegThreshold_ <= _MAX_DEPEG_THRESHOLD, "invalid depeg threshold");
require(newDepegThreshold_ != depegThreshold, "same as current");
depegThreshold = newDepegThreshold_;
emit DepegThresholdUpdated(newDepegThreshold_);
}
/// @notice Called when an underlying of a Curve Pool has depegged and we want to exit the pool./// Will check if a coin has depegged, and will revert if not./// Sets the weight of the Curve Pool to 0, and re-enables CNC rewards for deposits./// @dev Cannot be called if the underlying of this pool itself has depegged./// @param curvePool_ The Curve Pool to handle.functionhandleDepeggedCurvePool(address curvePool_) externaloverride{
runSanityChecks();
require(!_isAssetDepegged(address(underlying)), "underlying is depegged");
require(_isPoolDepegged(curvePool_), "pool is not depegged");
weightManager.handleDepeggedCurvePool(curvePool_);
// Updating total deviation
(
uint256 totalUnderlying_,
,
uint256[] memory allocatedPerPool
) = getTotalAndPerPoolUnderlying();
uint256 totalDeviation = weightManager.computeTotalDeviation(
totalUnderlying_,
allocatedPerPool
);
totalDeviationAfterWeightUpdate = totalDeviation;
if (rebalancingRewardsEnabled) {
IPoolAdapter poolAdapter = controller.poolAdapterFor(curvePool_);
uint256 usdValue = poolAdapter.computePoolValueInUSD(address(this), curvePool_);
if (usdValue > _MAX_USD_VALUE_FOR_REMOVING_POOL) {
// if the rebalancing rewards were already active// we reset the activated at because the rewards factor is now increased
rebalancingRewardsActivatedAt =uint64(block.timestamp);
rebalancingRewardsFactor = emergencyRebalancingRewardsFactor;
rebalancingRewardActive =true;
}
}
emit HandledDepeggedCurvePool(curvePool_);
}
/**
* @notice Allows anyone to set the weight of a Curve pool to 0 if the Convex pool for the
* associated PID has been shut down. This is a very unlikely outcome and the method does
* not reenable rebalancing rewards.
* @param curvePool_ Curve pool for which the Convex PID is invalid (has been shut down)
*/functionhandleInvalidConvexPid(address curvePool_) externaloverridereturns (uint256) {
runSanityChecks();
uint256 pid = weightManager.handleInvalidConvexPid(curvePool_);
emit HandledInvalidConvexPid(curvePool_, pid);
return pid;
}
functionsetMaxIdleCurveLpRatio(uint256 maxIdleCurveLpRatio_) externalonlyOwner{
require(maxIdleCurveLpRatio != maxIdleCurveLpRatio_, "same as current");
require(maxIdleCurveLpRatio_ <= _IDLE_RATIO_UPPER_BOUND, "ratio exceeds upper bound");
maxIdleCurveLpRatio = maxIdleCurveLpRatio_;
emit NewMaxIdleCurveLpRatio(maxIdleCurveLpRatio_);
}
functionsetMaxDeviation(uint256 maxDeviation_) externaloverrideonlyOwner{
require(maxDeviation != maxDeviation_, "same as current");
require(maxDeviation_ <= _MAX_DEVIATION_UPPER_BOUND, "deviation exceeds upper bound");
maxDeviation = maxDeviation_;
emit MaxDeviationUpdated(maxDeviation_);
}
functiongetWeight(address curvePool) externalviewoverridereturns (uint256) {
return weightManager.getWeight(curvePool);
}
functiongetWeights() externalviewoverridereturns (PoolWeight[] memory) {
return weightManager.getWeights();
}
functiongetAllocatedUnderlying() externalviewoverridereturns (PoolWithAmount[] memory) {
address[] memory pools = weightManager.allPools();
PoolWithAmount[] memory perPoolAllocated =new PoolWithAmount[](pools.length);
(, , uint256[] memory allocated) = getTotalAndPerPoolUnderlying();
for (uint256 i; i < perPoolAllocated.length; i++) {
perPoolAllocated[i] = PoolWithAmount(pools[i], allocated[i]);
}
return perPoolAllocated;
}
functioncomputeTotalDeviation() externalviewoverridereturns (uint256) {
(
,
uint256 allocatedUnderlying_,
uint256[] memory perPoolUnderlying
) = getTotalAndPerPoolUnderlying();
return weightManager.computeTotalDeviation(allocatedUnderlying_, perPoolUnderlying);
}
functioncachedTotalUnderlying() publicviewvirtualoverridereturns (uint256) {
if (block.timestamp> _cacheUpdatedTimestamp + _TOTAL_UNDERLYING_CACHE_EXPIRY) {
return totalUnderlying();
}
return _cachedTotalUnderlying;
}
functiongetTotalAndPerPoolUnderlying()
publicviewreturns (uint256 totalUnderlying_,
uint256 totalAllocated_,
uint256[] memory perPoolUnderlying_
)
{
uint256 underlyingPrice_ = controller.priceOracle().getUSDPrice(address(underlying));
return _getTotalAndPerPoolUnderlying(underlyingPrice_, IPoolAdapter.PriceMode.Latest);
}
functionisBalanced() externalviewoverridereturns (bool) {
(
,
uint256 allocatedUnderlying_,
uint256[] memory allocatedPerPool_
) = getTotalAndPerPoolUnderlying();
return _isBalanced(allocatedPerPool_, allocatedUnderlying_);
}
functionsetRebalancingRewardsEnabled(bool enabled) externaloverrideonlyOwner{
require(rebalancingRewardsEnabled != enabled, "same as current");
rebalancingRewardsEnabled = enabled;
emit RebalancingRewardsEnabledSet(enabled);
}
functionsetEmergencyRebalancingRewardFactor(uint256 factor_) externalonlyOwner{
require(factor_ >= _MIN_EMERGENCY_REBALANCING_REWARD_FACTOR, "factor below minimum");
require(factor_ <= _MAX_EMERGENCY_REBALANCING_REWARD_FACTOR, "factor above maximum");
require(factor_ != emergencyRebalancingRewardsFactor, "same as current");
emergencyRebalancingRewardsFactor = factor_;
emit EmergencyRebalancingRewardFactorUpdated(factor_);
}
function_updateAdapterCachedPrices() internal{
address[] memory pools = weightManager.allPools();
uint256 poolsLength_ = pools.length;
for (uint256 i; i < poolsLength_; i++) {
address pool_ = pools[i];
IPoolAdapter poolAdapter = controller.poolAdapterFor(pool_);
poolAdapter.updatePriceCache(pool_);
}
}
/**
* @notice Returns several values related to the Omnipools's underlying assets.
* @param underlyingPrice_ Price of the underlying asset in USD
* @return totalUnderlying_ Total underlying value of the Omnipool
* @return totalAllocated_ Total underlying value of the Omnipool that is allocated to Curve pools
* @return perPoolUnderlying_ Array of underlying values of the Omnipool that is allocated to each Curve pool
*/function_getTotalAndPerPoolUnderlying(uint256 underlyingPrice_,
IPoolAdapter.PriceMode priceMode
)
internalviewreturns (uint256 totalUnderlying_,
uint256 totalAllocated_,
uint256[] memory perPoolUnderlying_
)
{
address[] memory pools = weightManager.allPools();
uint256 poolsLength_ = pools.length;
perPoolUnderlying_ =newuint256[](poolsLength_);
for (uint256 i; i < poolsLength_; i++) {
address pool_ = pools[i];
uint256 poolUnderlying_ = controller.poolAdapterFor(pool_).computePoolValueInUnderlying(
address(this),
pool_,
address(underlying),
underlyingPrice_,
priceMode
);
perPoolUnderlying_[i] = poolUnderlying_;
totalAllocated_ += poolUnderlying_;
}
totalUnderlying_ = totalAllocated_ + underlying.balanceOf(address(this));
}
function_handleRebalancingRewards(address account,
uint256 allocatedBalanceBefore_,
uint256[] memory allocatedPerPoolBefore,
uint256 allocatedBalanceAfter_,
uint256[] memory allocatedPerPoolAfter
) internal{
if (!rebalancingRewardActive) return;
uint256 deviationBefore = weightManager.computeTotalDeviation(
allocatedBalanceBefore_,
allocatedPerPoolBefore
);
uint256 deviationAfter = weightManager.computeTotalDeviation(
allocatedBalanceAfter_,
allocatedPerPoolAfter
);
controller.inflationManager().handleRebalancingRewards(
account,
deviationBefore,
deviationAfter
);
if (_isBalanced(allocatedPerPoolAfter, allocatedBalanceAfter_)) {
rebalancingRewardActive =false;
}
}
function_min(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
function_isBalanced(uint256[] memory allocatedPerPool_,
uint256 totalAllocated_
) internalviewreturns (bool) {
return weightManager.isBalanced(allocatedPerPool_, totalAllocated_, maxDeviation);
}
functiongetAllUnderlyingCoins() publicviewreturns (address[] memory) {
address[] memory pools = weightManager.allPools();
uint256 poolsLength_ = pools.length;
address[] memory underlyings_ =newaddress[](0);
for (uint256 i; i < poolsLength_; i++) {
address pool_ = pools[i];
address[] memory coins = controller.poolAdapterFor(pool_).getAllUnderlyingCoins(pool_);
underlyings_ = underlyings_.concat(coins);
}
return underlyings_.removeDuplicates();
}
function_isPoolDepegged(address pool_) internalviewreturns (bool) {
address[] memory coins = controller.poolAdapterFor(pool_).getAllUnderlyingCoins(pool_);
for (uint256 i; i < coins.length; i++) {
address coin = coins[i];
if (_isAssetDepegged(coin)) returntrue;
}
returnfalse;
}
functionrunSanityChecks() publicvirtual{}
function_getMaxDeviation() internalviewreturns (uint256) {
return rebalancingRewardActive ? 0 : maxDeviation;
}
function_updatePriceCache() internalvirtual;
function_isAssetDepegged(address asset_) internalviewvirtualreturns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;import"EnumerableSet.sol";
import"EnumerableMap.sol";
import"SafeERC20.sol";
import"IConicPool.sol";
import"IConicPoolWeightManager.sol";
import"ScaledMath.sol";
contractConicPoolWeightManagerisIConicPoolWeightManager{
usingEnumerableSetforEnumerableSet.AddressSet;
usingEnumerableMapforEnumerableMap.AddressToUintMap;
usingScaledMathforuint256;
usingSafeERC20forIERC20;
eventCurvePoolAdded(address curvePool_);
eventCurvePoolRemoved(address curvePool_);
eventNewWeight(addressindexed curvePool, uint256 newWeight);
uint256internalconstant _MAX_USD_VALUE_FOR_REMOVING_POOL =100e18;
uint256internalconstant _MAX_CURVE_POOLS =10;
IConicPool publicimmutable conicPool;
IController publicimmutable controller;
IERC20Metadata publicimmutable underlying;
EnumerableSet.AddressSet internal _pools;
EnumerableMap.AddressToUintMap internal weights; // liquidity allocation weightsmodifieronlyController() {
require(msg.sender==address(controller), "not authorized");
_;
}
modifieronlyConicPool() {
require(msg.sender==address(conicPool), "not authorized");
_;
}
constructor(IController _controller, IERC20Metadata _underlying) {
conicPool = IConicPool(msg.sender);
controller = _controller;
underlying = _underlying;
}
functionaddPool(address _pool) externalonlyConicPool{
require(_pools.length() < _MAX_CURVE_POOLS, "max pools reached");
require(!_pools.contains(_pool), "pool already added");
IPoolAdapter poolAdapter = controller.poolAdapterFor(_pool);
bool supported_ = poolAdapter.supportsAsset(_pool, address(underlying));
require(supported_, "coin not in pool");
address lpToken_ = poolAdapter.lpToken(_pool);
require(controller.priceOracle().isTokenSupported(lpToken_), "cannot price LP Token");
if (!weights.contains(_pool)) weights.set(_pool, 0);
require(_pools.add(_pool), "failed to add pool");
emit CurvePoolAdded(_pool);
}
// This requires that the weight of the pool is first set to 0functionremovePool(address _pool) externalonlyConicPool{
require(_pools.contains(_pool), "pool not added");
require(_pools.length() >1, "cannot remove last pool");
IPoolAdapter poolAdapter = controller.poolAdapterFor(_pool);
uint256 usdValue = poolAdapter.computePoolValueInUSD(address(conicPool), _pool);
require(usdValue < _MAX_USD_VALUE_FOR_REMOVING_POOL, "pool has allocated funds");
uint256 weight = weights.get(_pool);
require(weight ==0, "pool has weight set");
require(_pools.remove(_pool), "pool not removed");
require(weights.remove(_pool), "weight not removed");
emit CurvePoolRemoved(_pool);
}
functionupdateWeights(PoolWeight[] memory poolWeights) externalonlyConicPool{
require(poolWeights.length== _pools.length(), "invalid pool weights");
uint256 total;
address previousPool;
for (uint256 i; i < poolWeights.length; i++) {
address pool_ = poolWeights[i].poolAddress;
require(pool_ > previousPool, "pools not sorted");
require(isRegisteredPool(pool_), "pool is not registered");
uint256 newWeight = poolWeights[i].weight;
weights.set(pool_, newWeight);
emit NewWeight(pool_, newWeight);
total += newWeight;
previousPool = pool_;
}
require(total == ScaledMath.ONE, "weights do not sum to 1");
}
functionhandleDepeggedCurvePool(address curvePool_) externalonlyConicPool{
// Validationrequire(isRegisteredPool(curvePool_), "pool is not registered");
require(weights.get(curvePool_) !=0, "pool weight already 0");
// Set target curve pool weight to 0// Scale up other weights to compensate
_setWeightToZero(curvePool_);
}
functionhandleInvalidConvexPid(address curvePool_) externalonlyConicPoolreturns (uint256) {
require(isRegisteredPool(curvePool_), "curve pool not registered");
ICurveRegistryCache registryCache_ = controller.curveRegistryCache();
uint256 pid = registryCache_.getPid(curvePool_);
require(registryCache_.isShutdownPid(pid), "convex pool pid is not shut down");
_setWeightToZero(curvePool_);
return pid;
}
functiongetDepositPool(uint256 totalUnderlying_,
uint256[] memory allocatedPerPool,
uint256 maxDeviation
) externalviewreturns (uint256 poolIndex, uint256 maxDepositAmount) {
uint256 poolsCount_ = allocatedPerPool.length;
int256 iPoolIndex =-1;
for (uint256 i; i < poolsCount_; i++) {
address pool_ = _pools.at(i);
uint256 allocatedUnderlying_ = allocatedPerPool[i];
uint256 weight_ = weights.get(pool_);
uint256 targetAllocation_ = totalUnderlying_.mulDown(weight_);
if (allocatedUnderlying_ >= targetAllocation_) continue;
// Compute max balance with deviationuint256 weightWithDeviation_ = weight_.mulDown(ScaledMath.ONE + maxDeviation);
weightWithDeviation_ = weightWithDeviation_ > ScaledMath.ONE
? ScaledMath.ONE
: weightWithDeviation_;
uint256 maxBalance_ = totalUnderlying_.mulDown(weightWithDeviation_);
uint256 maxDepositAmount_ = maxBalance_ - allocatedUnderlying_;
if (maxDepositAmount_ <= maxDepositAmount) continue;
maxDepositAmount = maxDepositAmount_;
iPoolIndex =int256(i);
}
require(iPoolIndex >-1, "error retrieving deposit pool");
poolIndex =uint256(iPoolIndex);
}
functiongetWithdrawPool(uint256 totalUnderlying_,
uint256[] memory allocatedPerPool,
uint256 maxDeviation
) externalviewreturns (uint256 withdrawPoolIndex, uint256 maxWithdrawalAmount) {
uint256 poolsCount_ = allocatedPerPool.length;
int256 iWithdrawPoolIndex =-1;
for (uint256 i; i < poolsCount_; i++) {
address curvePool_ = _pools.at(i);
uint256 weight_ = weights.get(curvePool_);
uint256 allocatedUnderlying_ = allocatedPerPool[i];
// If a pool has a weight of 0,// withdraw from it if it has more than the max lp valueif (weight_ ==0) {
uint256 price_ = controller.priceOracle().getUSDPrice(address(underlying));
uint256 allocatedUsd = (price_ * allocatedUnderlying_) /10** underlying.decimals();
if (allocatedUsd >= _MAX_USD_VALUE_FOR_REMOVING_POOL /2) {
return (uint256(i), allocatedUnderlying_);
}
}
uint256 targetAllocation_ = totalUnderlying_.mulDown(weight_);
if (allocatedUnderlying_ <= targetAllocation_) continue;
uint256 minBalance_ = targetAllocation_ - targetAllocation_.mulDown(maxDeviation);
uint256 maxWithdrawalAmount_ = allocatedUnderlying_ - minBalance_;
if (maxWithdrawalAmount_ <= maxWithdrawalAmount) continue;
maxWithdrawalAmount = maxWithdrawalAmount_;
iWithdrawPoolIndex =int256(i);
}
require(iWithdrawPoolIndex >-1, "error retrieving withdraw pool");
withdrawPoolIndex =uint256(iWithdrawPoolIndex);
}
functionallPools() externalviewreturns (address[] memory) {
return _pools.values();
}
functionpoolsCount() externalviewreturns (uint256) {
return _pools.length();
}
functiongetPoolAtIndex(uint256 _index) externalviewreturns (address) {
return _pools.at(_index);
}
functionisRegisteredPool(address _pool) publicviewreturns (bool) {
return _pools.contains(_pool);
}
functiongetWeight(address pool) externalviewreturns (uint256) {
return weights.get(pool);
}
functiongetWeights() externalviewreturns (IConicPool.PoolWeight[] memory) {
uint256 length_ = _pools.length();
IConicPool.PoolWeight[] memory weights_ =new IConicPool.PoolWeight[](length_);
for (uint256 i; i < length_; i++) {
(address pool_, uint256 weight_) = weights.at(i);
weights_[i] = PoolWeight(pool_, weight_);
}
return weights_;
}
functioncomputeTotalDeviation(uint256 allocatedUnderlying_,
uint256[] memory perPoolAllocations_
) externalviewreturns (uint256) {
uint256 totalDeviation;
for (uint256 i; i < perPoolAllocations_.length; i++) {
uint256 weight = weights.get(_pools.at(i));
uint256 targetAmount = allocatedUnderlying_.mulDown(weight);
totalDeviation += targetAmount.absSub(perPoolAllocations_[i]);
}
return totalDeviation;
}
functionisBalanced(uint256[] memory allocatedPerPool_,
uint256 totalAllocated_,
uint256 maxDeviation
) externalviewreturns (bool) {
if (totalAllocated_ ==0) returntrue;
for (uint256 i; i < allocatedPerPool_.length; i++) {
uint256 weight_ = weights.get(_pools.at(i));
uint256 currentAllocated_ = allocatedPerPool_[i];
// If a curve pool has a weight of 0,if (weight_ ==0) {
uint256 price_ = controller.priceOracle().getUSDPrice(address(underlying));
uint256 allocatedUsd_ = (price_ * currentAllocated_) /10** underlying.decimals();
if (allocatedUsd_ >= _MAX_USD_VALUE_FOR_REMOVING_POOL /2) {
returnfalse;
}
continue;
}
uint256 targetAmount = totalAllocated_.mulDown(weight_);
uint256 deviation = targetAmount.absSub(currentAllocated_);
uint256 deviationRatio = deviation.divDown(targetAmount);
if (deviationRatio > maxDeviation) returnfalse;
}
returntrue;
}
function_setWeightToZero(address zeroedPool) internal{
uint256 weight_ = weights.get(zeroedPool);
if (weight_ ==0) return;
require(weight_ != ScaledMath.ONE, "can't remove last pool");
uint256 scaleUp_ = ScaledMath.ONE.divDown(ScaledMath.ONE - weights.get(zeroedPool));
uint256 curvePoolLength_ = _pools.length();
weights.set(zeroedPool, 0);
emit NewWeight(zeroedPool, 0);
address[] memory nonZeroPools =newaddress[](curvePoolLength_ -1);
uint256[] memory nonZeroWeights =newuint256[](curvePoolLength_ -1);
uint256 nonZeroPoolsCount;
for (uint256 i; i < curvePoolLength_; i++) {
address pool_ = _pools.at(i);
uint256 currentWeight = weights.get(pool_);
if (currentWeight ==0) continue;
nonZeroPools[nonZeroPoolsCount] = pool_;
nonZeroWeights[nonZeroPoolsCount] = currentWeight;
nonZeroPoolsCount++;
}
uint256 totalWeight;
for (uint256 i; i < nonZeroPoolsCount; i++) {
address pool_ = nonZeroPools[i];
uint256 newWeight_ = nonZeroWeights[i].mulDown(scaleUp_);
// ensure that the sum of the weights is 1 despite potential rounding errorsif (i == nonZeroPoolsCount -1) {
newWeight_ = ScaledMath.ONE - totalWeight;
}
totalWeight += newWeight_;
weights.set(pool_, newWeight_);
emit NewWeight(pool_, newWeight_);
}
}
}
Contract Source Code
File 6 of 40: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 7 of 40: CurvePoolUtils.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;import"ICurvePoolV2.sol";
import"ICurvePoolV1.sol";
import"ScaledMath.sol";
libraryCurvePoolUtils{
usingScaledMathforuint256;
errorNotWithinThreshold(address pool, uint256 assetA, uint256 assetB);
/// @dev by default, allow for 30 bps deviation regardless of pool feesuint256internalconstant _DEFAULT_IMBALANCE_BUFFER =30e14;
/// @dev Curve scales the `fee` by 1e10uint8internalconstant _CURVE_POOL_FEE_DECIMALS =10;
/// @dev allow imbalance to be buffer + 3x the fee, e.g. if fee is 3.6 bps and buffer is 30 bps, allow 40.8 bpsuint256internalconstant _FEE_IMBALANCE_MULTIPLIER =3;
enumAssetType {
USD,
ETH,
BTC,
OTHER,
CRYPTO
}
structPoolMeta {
address pool;
uint256 numberOfCoins;
AssetType assetType;
uint256[] decimals;
uint256[] prices;
uint256[] imbalanceBuffers;
}
functionensurePoolBalanced(PoolMeta memory poolMeta) internalview{
uint256 poolFee = ICurvePoolV1(poolMeta.pool).fee().convertScale(
_CURVE_POOL_FEE_DECIMALS,
18
);
for (uint256 i =0; i < poolMeta.numberOfCoins -1; i++) {
uint256 fromDecimals = poolMeta.decimals[i];
uint256 fromBalance =10** fromDecimals;
uint256 fromPrice = poolMeta.prices[i];
for (uint256 j = i +1; j < poolMeta.numberOfCoins; j++) {
uint256 toDecimals = poolMeta.decimals[j];
uint256 toPrice = poolMeta.prices[j];
uint256 toExpectedUnscaled = (fromBalance * fromPrice) / toPrice;
uint256 toExpected = toExpectedUnscaled.convertScale(
uint8(fromDecimals),
uint8(toDecimals)
);
uint256 toActual;
if (poolMeta.assetType == AssetType.CRYPTO) {
// Handling crypto pools
toActual = ICurvePoolV2(poolMeta.pool).get_dy(i, j, fromBalance);
} else {
// Handling other pools
toActual = ICurvePoolV1(poolMeta.pool).get_dy(
int128(uint128(i)),
int128(uint128(j)),
fromBalance
);
}
uint256 _maxImbalanceBuffer = poolMeta.imbalanceBuffers[i].max(
poolMeta.imbalanceBuffers[j]
);
if (!_isWithinThreshold(toExpected, toActual, poolFee, _maxImbalanceBuffer))
revert NotWithinThreshold(poolMeta.pool, i, j);
}
}
}
function_isWithinThreshold(uint256 a,
uint256 b,
uint256 poolFee,
uint256 imbalanceBuffer
) internalpurereturns (bool) {
if (imbalanceBuffer ==0) imbalanceBuffer = _DEFAULT_IMBALANCE_BUFFER;
uint256 imbalanceTreshold = imbalanceBuffer + poolFee * _FEE_IMBALANCE_MULTIPLIER;
if (a > b) return (a - b).divDown(a) <= imbalanceTreshold;
return (b - a).divDown(b) <= imbalanceTreshold;
}
}
Contract Source Code
File 8 of 40: ERC165Checker.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/ERC165Checker.sol)pragmasolidity ^0.8.0;import"IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/libraryERC165Checker{
// As per the EIP-165 spec, no interface should ever match 0xffffffffbytes4privateconstant _INTERFACE_ID_INVALID =0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface.
*/functionsupportsERC165(address account) internalviewreturns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalidreturn
supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) &&!supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/functionsupportsInterface(address account, bytes4 interfaceId) internalviewreturns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceIdreturn supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/functiongetSupportedInterfaces(address account,
bytes4[] memory interfaceIds
) internalviewreturns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or notbool[] memory interfaceIdsSupported =newbool[](interfaceIds.length);
// query support of ERC165 itselfif (supportsERC165(account)) {
// query support of each interface in interfaceIdsfor (uint256 i =0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/functionsupportsAllInterfaces(address account, bytes4[] memory interfaceIds) internalviewreturns (bool) {
// query support of ERC165 itselfif (!supportsERC165(account)) {
returnfalse;
}
// query support of each interface in interfaceIdsfor (uint256 i =0; i < interfaceIds.length; i++) {
if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
returnfalse;
}
}
// all interfaces supportedreturntrue;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
*
* Some precompiled contracts will falsely indicate support for a given interface, so caution
* should be exercised when using this function.
*
* Interface identification is specified in ERC-165.
*/functionsupportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internalviewreturns (bool) {
// prepare callbytesmemory encodedParams =abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
// perform static callbool success;
uint256 returnSize;
uint256 returnValue;
assembly {
success :=staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
returnSize :=returndatasize()
returnValue :=mload(0x00)
}
return success && returnSize >=0x20&& returnValue >0;
}
}
Contract Source Code
File 9 of 40: ERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)pragmasolidity ^0.8.0;import"IERC20.sol";
import"IERC20Metadata.sol";
import"Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/contractERC20isContext, IERC20, IERC20Metadata{
mapping(address=>uint256) private _balances;
mapping(address=>mapping(address=>uint256)) private _allowances;
uint256private _totalSupply;
stringprivate _name;
stringprivate _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
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}.
*/functiondecimals() publicviewvirtualoverridereturns (uint8) {
return18;
}
/**
* @dev See {IERC20-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/functionbalanceOf(address account) publicviewvirtualoverridereturns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/functiontransfer(address to, uint256 amount) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
returntrue;
}
/**
* @dev See {IERC20-allowance}.
*/functionallowance(address owner, address spender) publicviewvirtualoverridereturns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionapprove(address spender, uint256 amount) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
returntrue;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/functiontransferFrom(addressfrom, address to, uint256 amount) publicvirtualoverridereturns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
returntrue;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionincreaseAllowance(address spender, uint256 addedValue) publicvirtualreturns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
returntrue;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/functiondecreaseAllowance(address spender, uint256 subtractedValue) publicvirtualreturns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
returntrue;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/function_transfer(addressfrom, address to, uint256 amount) internalvirtual{
require(from!=address(0), "ERC20: transfer from the zero address");
require(to !=address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/function_mint(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/function_burn(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/function_approve(address owner, address spender, uint256 amount) internalvirtual{
require(owner !=address(0), "ERC20: approve from the zero address");
require(spender !=address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/function_spendAllowance(address owner, address spender, uint256 amount) internalvirtual{
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance !=type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom, address to, uint256 amount) internalvirtual{}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_afterTokenTransfer(addressfrom, address to, uint256 amount) internalvirtual{}
}
Contract Source Code
File 10 of 40: EnumerableMap.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableMap.sol)// This file was procedurally generated from scripts/generate/templates/EnumerableMap.js.pragmasolidity ^0.8.0;import"EnumerableSet.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* The following map types are supported:
*
* - `uint256 -> address` (`UintToAddressMap`) since v3.0.0
* - `address -> uint256` (`AddressToUintMap`) since v4.6.0
* - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0
* - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0
* - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableMap.
* ====
*/libraryEnumerableMap{
usingEnumerableSetforEnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code// repetition as possible, we write it in terms of a generic Map type with// bytes32 keys and values.// The Map implementation uses private functions, and user-facing// implementations (such as Uint256ToAddressMap) are just wrappers around// the underlying Map.// This means that we can only create new EnumerableMaps for types that fit// in bytes32.structBytes32ToBytes32Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32=>bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/functionset(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internalreturns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/functionremove(Bytes32ToBytes32Map storage map, bytes32 key) internalreturns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/functioncontains(Bytes32ToBytes32Map storage map, bytes32 key) internalviewreturns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/functionlength(Bytes32ToBytes32Map storage map) internalviewreturns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/functionat(Bytes32ToBytes32Map storage map, uint256 index) internalviewreturns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/functiontryGet(Bytes32ToBytes32Map storage map, bytes32 key) internalviewreturns (bool, bytes32) {
bytes32 value = map._values[key];
if (value ==bytes32(0)) {
return (contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/functionget(Bytes32ToBytes32Map storage map, bytes32 key) internalviewreturns (bytes32) {
bytes32 value = map._values[key];
require(value !=0|| contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/functionget(
Bytes32ToBytes32Map storage map,
bytes32 key,
stringmemory errorMessage
) internalviewreturns (bytes32) {
bytes32 value = map._values[key];
require(value !=0|| contains(map, key), errorMessage);
return value;
}
/**
* @dev Return the an array containing all the keys
*
* 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionkeys(Bytes32ToBytes32Map storage map) internalviewreturns (bytes32[] memory) {
return map._keys.values();
}
// UintToUintMapstructUintToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/functionset(UintToUintMap storage map, uint256 key, uint256 value) internalreturns (bool) {
return set(map._inner, bytes32(key), bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/functionremove(UintToUintMap storage map, uint256 key) internalreturns (bool) {
return remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/functioncontains(UintToUintMap storage map, uint256 key) internalviewreturns (bool) {
return contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/functionlength(UintToUintMap storage map) internalviewreturns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. 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}.
*/functionat(UintToUintMap storage map, uint256 index) internalviewreturns (uint256, uint256) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (uint256(key), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/functiontryGet(UintToUintMap storage map, uint256 key) internalviewreturns (bool, uint256) {
(bool success, bytes32 value) = tryGet(map._inner, bytes32(key));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/functionget(UintToUintMap storage map, uint256 key) internalviewreturns (uint256) {
returnuint256(get(map._inner, bytes32(key)));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/functionget(UintToUintMap storage map, uint256 key, stringmemory errorMessage) internalviewreturns (uint256) {
returnuint256(get(map._inner, bytes32(key), errorMessage));
}
/**
* @dev Return the an array containing all the keys
*
* 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionkeys(UintToUintMap storage map) internalviewreturns (uint256[] memory) {
bytes32[] memory store = keys(map._inner);
uint256[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// UintToAddressMapstructUintToAddressMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/functionset(UintToAddressMap storage map, uint256 key, address value) internalreturns (bool) {
return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/functionremove(UintToAddressMap storage map, uint256 key) internalreturns (bool) {
return remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/functioncontains(UintToAddressMap storage map, uint256 key) internalviewreturns (bool) {
return contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/functionlength(UintToAddressMap storage map) internalviewreturns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. 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}.
*/functionat(UintToAddressMap storage map, uint256 index) internalviewreturns (uint256, address) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/functiontryGet(UintToAddressMap storage map, uint256 key) internalviewreturns (bool, address) {
(bool success, bytes32 value) = tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/functionget(UintToAddressMap storage map, uint256 key) internalviewreturns (address) {
returnaddress(uint160(uint256(get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/functionget(
UintToAddressMap storage map,
uint256 key,
stringmemory errorMessage
) internalviewreturns (address) {
returnaddress(uint160(uint256(get(map._inner, bytes32(key), errorMessage))));
}
/**
* @dev Return the an array containing all the keys
*
* 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionkeys(UintToAddressMap storage map) internalviewreturns (uint256[] memory) {
bytes32[] memory store = keys(map._inner);
uint256[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// AddressToUintMapstructAddressToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/functionset(AddressToUintMap storage map, address key, uint256 value) internalreturns (bool) {
return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/functionremove(AddressToUintMap storage map, address key) internalreturns (bool) {
return remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/functioncontains(AddressToUintMap storage map, address key) internalviewreturns (bool) {
return contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/functionlength(AddressToUintMap storage map) internalviewreturns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. 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}.
*/functionat(AddressToUintMap storage map, uint256 index) internalviewreturns (address, uint256) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (address(uint160(uint256(key))), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/functiontryGet(AddressToUintMap storage map, address key) internalviewreturns (bool, uint256) {
(bool success, bytes32 value) = tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/functionget(AddressToUintMap storage map, address key) internalviewreturns (uint256) {
returnuint256(get(map._inner, bytes32(uint256(uint160(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/functionget(
AddressToUintMap storage map,
address key,
stringmemory errorMessage
) internalviewreturns (uint256) {
returnuint256(get(map._inner, bytes32(uint256(uint160(key))), errorMessage));
}
/**
* @dev Return the an array containing all the keys
*
* 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionkeys(AddressToUintMap storage map) internalviewreturns (address[] memory) {
bytes32[] memory store = keys(map._inner);
address[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// Bytes32ToUintMapstructBytes32ToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/functionset(Bytes32ToUintMap storage map, bytes32 key, uint256 value) internalreturns (bool) {
return set(map._inner, key, bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/functionremove(Bytes32ToUintMap storage map, bytes32 key) internalreturns (bool) {
return remove(map._inner, key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/functioncontains(Bytes32ToUintMap storage map, bytes32 key) internalviewreturns (bool) {
return contains(map._inner, key);
}
/**
* @dev Returns the number of elements in the map. O(1).
*/functionlength(Bytes32ToUintMap storage map) internalviewreturns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. 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}.
*/functionat(Bytes32ToUintMap storage map, uint256 index) internalviewreturns (bytes32, uint256) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (key, uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/functiontryGet(Bytes32ToUintMap storage map, bytes32 key) internalviewreturns (bool, uint256) {
(bool success, bytes32 value) = tryGet(map._inner, key);
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/functionget(Bytes32ToUintMap storage map, bytes32 key) internalviewreturns (uint256) {
returnuint256(get(map._inner, key));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/functionget(
Bytes32ToUintMap storage map,
bytes32 key,
stringmemory errorMessage
) internalviewreturns (uint256) {
returnuint256(get(map._inner, key, errorMessage));
}
/**
* @dev Return the an array containing all the keys
*
* 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionkeys(Bytes32ToUintMap storage map) internalviewreturns (bytes32[] memory) {
bytes32[] memory store = keys(map._inner);
bytes32[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
}
Contract Source Code
File 11 of 40: EnumerableSet.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.pragmasolidity ^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.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/libraryEnumerableSet{
// 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.structSet {
// Storage of set valuesbytes32[] _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) privatereturns (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;
returntrue;
} else {
returnfalse;
}
}
/**
* @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) privatereturns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slotuint256 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 slotdelete set._indexes[value];
returntrue;
} else {
returnfalse;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/function_contains(Set storage set, bytes32 value) privateviewreturns (bool) {
return set._indexes[value] !=0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/function_length(Set storage set) privateviewreturns (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) privateviewreturns (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) privateviewreturns (bytes32[] memory) {
return set._values;
}
// Bytes32SetstructBytes32Set {
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.
*/functionadd(Bytes32Set storage set, bytes32 value) internalreturns (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.
*/functionremove(Bytes32Set storage set, bytes32 value) internalreturns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(Bytes32Set storage set, bytes32 value) internalviewreturns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(Bytes32Set storage set) internalviewreturns (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}.
*/functionat(Bytes32Set storage set, uint256 index) internalviewreturns (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.
*/functionvalues(Bytes32Set storage set) internalviewreturns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// AddressSetstructAddressSet {
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.
*/functionadd(AddressSet storage set, address value) internalreturns (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.
*/functionremove(AddressSet storage set, address value) internalreturns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(AddressSet storage set, address value) internalviewreturns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(AddressSet storage set) internalviewreturns (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}.
*/functionat(AddressSet storage set, uint256 index) internalviewreturns (address) {
returnaddress(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.
*/functionvalues(AddressSet storage set) internalviewreturns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// UintSetstructUintSet {
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.
*/functionadd(UintSet storage set, uint256 value) internalreturns (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.
*/functionremove(UintSet storage set, uint256 value) internalreturns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(UintSet storage set, uint256 value) internalviewreturns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(UintSet storage set) internalviewreturns (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}.
*/functionat(UintSet storage set, uint256 index) internalviewreturns (uint256) {
returnuint256(_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.
*/functionvalues(UintSet storage set) internalviewreturns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;import"IBooster.sol";
import"CurvePoolUtils.sol";
interfaceICurveRegistryCache{
eventPoolInitialized(addressindexed pool, uint256indexed pid);
functionBOOSTER() externalviewreturns (IBooster);
functioninitPool(address pool_) external;
functioninitPool(address pool_, uint256 pid_) external;
functionlpToken(address pool_) externalviewreturns (address);
functionassetType(address pool_) externalviewreturns (CurvePoolUtils.AssetType);
functionisRegistered(address pool_) externalviewreturns (bool);
functionhasCoinDirectly(address pool_, address coin_) externalviewreturns (bool);
functionhasCoinAnywhere(address pool_, address coin_) externalviewreturns (bool);
functionbasePool(address pool_) externalviewreturns (address);
functioncoinIndex(address pool_, address coin_) externalviewreturns (int128);
functionnCoins(address pool_) externalviewreturns (uint256);
functioncoinIndices(address pool_,
address from_,
address to_
) externalviewreturns (int128, int128, bool);
functiondecimals(address pool_) externalviewreturns (uint256[] memory);
functioninterfaceVersion(address pool_) externalviewreturns (uint256);
functionpoolFromLpToken(address lpToken_) externalviewreturns (address);
functioncoins(address pool_) externalviewreturns (address[] memory);
functiongetPid(address _pool) externalviewreturns (uint256);
functiongetRewardPool(address _pool) externalviewreturns (address);
functionisShutdownPid(uint256 pid_) externalviewreturns (bool);
/// @notice this returns the underlying coins of a pool, including the underlying of the base pool/// if the given pool is a meta pool/// This does not return the LP token of the base pool as an underlying/// e.g. if the pool is 3CrvFrax, this will return FRAX, DAI, USDC, USDTfunctiongetAllUnderlyingCoins(address pool) externalviewreturns (address[] memory);
}
Contract Source Code
File 22 of 40: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165{
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 23 of 40: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (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.
*/functiontransfer(address to, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (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.
*/functionapprove(address spender, uint256 amount) externalreturns (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.
*/functiontransferFrom(addressfrom, address to, uint256 amount) externalreturns (bool);
}
Contract Source Code
File 24 of 40: IERC20Metadata.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)pragmasolidity ^0.8.0;import"IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Contract Source Code
File 25 of 40: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^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.
*/interfaceIERC20Permit{
/**
* @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].
*/functionpermit(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.
*/functionnonces(address owner) externalviewreturns (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-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;import"IOracle.sol";
interfaceIGenericOracleisIOracle{
/// @notice returns the oracle to be used to price `token`functiongetOracle(address token) externalviewreturns (IOracle);
/// @notice converts the price of an LP token to the given underlyingfunctioncurveLpToUnderlying(address curveLpToken,
address underlying,
uint256 curveLpAmount
) externalviewreturns (uint256);
/// @notice same as above but avoids fetching the underlying price againfunctioncurveLpToUnderlying(address curveLpToken,
address underlying,
uint256 curveLpAmount,
uint256 underlyingPrice
) externalviewreturns (uint256);
/// @notice converts the price an underlying asset to a given Curve LP tokenfunctionunderlyingToCurveLp(address underlying,
address curveLpToken,
uint256 underlyingAmount
) externalviewreturns (uint256);
}
Contract Source Code
File 28 of 40: IInflationManager.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;interfaceIInflationManager{
eventTokensClaimed(addressindexed pool, uint256 cncAmount);
eventRebalancingRewardHandlerAdded(addressindexed pool, addressindexed handler);
eventRebalancingRewardHandlerRemoved(addressindexed pool, addressindexed handler);
eventPoolWeightsUpdated();
functionexecuteInflationRateUpdate() external;
functionupdatePoolWeights() external;
/// @notice returns the weights of the Conic pools to know how much inflation/// each of them will receive, as well as the total amount of USD value in all the poolsfunctioncomputePoolWeights()
externalviewreturns (address[] memory _pools, uint256[] memory poolWeights, uint256 totalUSDValue);
functioncomputePoolWeight(address pool
) externalviewreturns (uint256 poolWeight, uint256 totalUSDValue);
functioncurrentInflationRate() externalviewreturns (uint256);
functiongetCurrentPoolInflationRate(address pool) externalviewreturns (uint256);
functionhandleRebalancingRewards(address account,
uint256 deviationBefore,
uint256 deviationAfter
) external;
functionaddPoolRebalancingRewardHandler(address poolAddress,
address rebalancingRewardHandler
) external;
functionremovePoolRebalancingRewardHandler(address poolAddress,
address rebalancingRewardHandler
) external;
functionrebalancingRewardHandlers(address poolAddress
) externalviewreturns (address[] memory);
functionhasPoolRebalancingRewardHandler(address poolAddress,
address handler
) externalviewreturns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;interfaceIOracle{
eventTokenUpdated(addressindexed token, address feed, uint256 maxDelay, bool isEthPrice);
/// @notice returns the price in USD of symbol.functiongetUSDPrice(address token) externalviewreturns (uint256);
/// @notice returns if the given token is supported for pricing.functionisTokenSupported(address token) externalviewreturns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;interfaceIPoolAdapter{
/// @notice This is to set which LP token price the value computation should use/// `Latest` uses a freshly computed price/// `Cached` uses the price in cache/// `Minimum` uses the minimum of these twoenumPriceMode {
Latest,
Cached,
Minimum
}
/// @notice Deposit `underlyingAmount` of `underlying` into `pool`/// @dev This function should be written with the assumption that it will be delegate-called intofunctiondeposit(address pool, address underlying, uint256 underlyingAmount) external;
/// @notice Withdraw `underlyingAmount` of `underlying` from `pool`/// @dev This function should be written with the assumption that it will be delegate-called intofunctionwithdraw(address pool, address underlying, uint256 underlyingAmount) external;
/// @notice Returns the amount of of assets that `conicPool` holds in `pool`, in terms of USDfunctioncomputePoolValueInUSD(address conicPool,
address pool
) externalviewreturns (uint256 usdAmount);
/// @notice Updates the price caches of the given poolsfunctionupdatePriceCache(address pool) external;
/// @notice Returns the amount of of assets that `conicPool` holds in `pool`, in terms of USD/// using the given price modefunctioncomputePoolValueInUSD(address conicPool,
address pool,
PriceMode priceMode
) externalviewreturns (uint256 usdAmount);
/// @notice Returns the amount of of assets that `conicPool` holds in `pool`, in terms of underlyingfunctioncomputePoolValueInUnderlying(address conicPool,
address pool,
address underlying,
uint256 underlyingPrice
) externalviewreturns (uint256 underlyingAmount);
/// @notice Returns the amount of of assets that `conicPool` holds in `pool`, in terms of underlying/// using the given price modefunctioncomputePoolValueInUnderlying(address conicPool,
address pool,
address underlying,
uint256 underlyingPrice,
PriceMode priceMode
) externalviewreturns (uint256 underlyingAmount);
/// @notice Claim earnings of `conicPool` from `pool`functionclaimEarnings(address conicPool, address pool) external;
/// @notice Returns the LP token of a given `pool`functionlpToken(address pool) externalviewreturns (address);
/// @notice Returns true if `pool` supports `asset`functionsupportsAsset(address pool, address asset) externalviewreturns (bool);
/// @notice Returns the amount of CRV earned by `pool` on ConvexfunctiongetCRVEarnedOnConvex(address account,
address curvePool
) externalviewreturns (uint256);
/// @notice Executes a sanity check, e.g. checking for reentrancyfunctionexecuteSanityCheck(address pool) external;
/// @notice returns all the underlying coins of the poolfunctiongetAllUnderlyingCoins(address pool) externalviewreturns (address[] memory);
}
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;import"ERC20.sol";
import"SafeERC20.sol";
import"IController.sol";
import"ILpToken.sol";
contractLpTokenisILpToken, ERC20{
IController publicimmutable controller;
addresspublicimmutableoverride minter;
modifieronlyMinter() {
require(msg.sender== minter, "not authorized");
_;
}
mapping(address=>uint256) internal _lastEvent;
uint8private __decimals;
constructor(address _controller,
address _minter,
uint8 _decimals,
stringmemory name_,
stringmemory symbol_
) ERC20(name_, symbol_) {
controller = IController(_controller);
minter = _minter;
__decimals = _decimals;
}
functiondecimals() publicviewvirtualoverride(ERC20, IERC20Metadata) returns (uint8) {
return __decimals;
}
functionmint(address _account,
uint256 _amount,
address ubo
) externaloverrideonlyMinterreturns (uint256) {
_ensureSingleEvent(ubo, _amount);
_mint(_account, _amount);
return _amount;
}
functionburn(address _owner,
uint256 _amount,
address ubo
) externaloverrideonlyMinterreturns (uint256) {
_ensureSingleEvent(ubo, _amount);
_burn(_owner, _amount);
return _amount;
}
functiontaint(addressfrom, address to, uint256 amount) external{
require(msg.sender==address(controller.lpTokenStaker()), "not authorized");
_taint(from, to, amount);
}
function_beforeTokenTransfer(addressfrom, address to, uint256 amount) internaloverride{
// mint/burn are handled in their respective functionsif (from==address(0) || to ==address(0)) return;
// lpTokenStaker calls `taint` as neededaddress lpTokenStaker =address(controller.lpTokenStaker());
if (from== lpTokenStaker || to == lpTokenStaker) return;
// taint any other type of transfer
_taint(from, to, amount);
}
function_ensureSingleEvent(address ubo, uint256 amount) internal{
if (
!controller.isAllowedMultipleDepositsWithdraws(ubo) &&
amount > controller.getMinimumTaintedTransferAmount(address(this))
) {
require(_lastEvent[ubo] !=block.number, "cannot mint/burn twice in a block");
_lastEvent[ubo] =block.number;
}
}
function_taint(addressfrom, address to, uint256 amount) internal{
if (
from!= to &&
_lastEvent[from] ==block.number&&
amount > controller.getMinimumTaintedTransferAmount(address(this))
) {
_lastEvent[to] =block.number;
}
}
}
Contract Source Code
File 37 of 40: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)pragmasolidity ^0.8.0;import"Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.0;import"IERC20.sol";
import"IERC20Permit.sol";
import"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.
*/librarySafeERC20{
usingAddressforaddress;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/functionsafeTransferFrom(IERC20 token, addressfrom, 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.
*/functionsafeApprove(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));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal{
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory approvalCall =abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/functionsafePermit(
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, bytesmemory 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.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length==0||abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation 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).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/function_callOptionalReturnBool(IERC20 token, bytesmemory data) privatereturns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false// and not revert is the subcall reverts.
(bool success, bytesmemory returndata) =address(token).call(data);
return
success && (returndata.length==0||abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
Contract Source Code
File 40 of 40: ScaledMath.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity 0.8.17;libraryScaledMath{
uint256internalconstant DECIMALS =18;
uint256internalconstant ONE =10** DECIMALS;
functionmulDown(uint256 a, uint256 b) internalpurereturns (uint256) {
return (a * b) / ONE;
}
functionmulDown(uint256 a, uint256 b, uint256 decimals) internalpurereturns (uint256) {
return (a * b) / (10** decimals);
}
functiondivDown(uint256 a, uint256 b) internalpurereturns (uint256) {
return (a * ONE) / b;
}
functiondivDown(uint256 a, uint256 b, uint256 decimals) internalpurereturns (uint256) {
return (a *10** decimals) / b;
}
functiondivUp(uint256 a, uint256 b) internalpurereturns (uint256) {
if (a ==0) {
return0;
}
return ((a * ONE) -1) / b +1;
}
functionmulDown(int256 a, int256 b) internalpurereturns (int256) {
return (a * b) /int256(ONE);
}
functionmulDownUint128(uint128 a, uint128 b) internalpurereturns (uint128) {
return (a * b) /uint128(ONE);
}
functionmulDown(int256 a, int256 b, uint256 decimals) internalpurereturns (int256) {
return (a * b) /int256(10** decimals);
}
functiondivDown(int256 a, int256 b) internalpurereturns (int256) {
return (a *int256(ONE)) / b;
}
functiondivDownUint128(uint128 a, uint128 b) internalpurereturns (uint128) {
return (a *uint128(ONE)) / b;
}
functiondivDown(int256 a, int256 b, uint256 decimals) internalpurereturns (int256) {
return (a *int256(10** decimals)) / b;
}
functionconvertScale(uint256 a,
uint8 fromDecimals,
uint8 toDecimals
) internalpurereturns (uint256) {
if (fromDecimals == toDecimals) return a;
if (fromDecimals > toDecimals) return downscale(a, fromDecimals, toDecimals);
return upscale(a, fromDecimals, toDecimals);
}
functionconvertScale(int256 a,
uint8 fromDecimals,
uint8 toDecimals
) internalpurereturns (int256) {
if (fromDecimals == toDecimals) return a;
if (fromDecimals > toDecimals) return downscale(a, fromDecimals, toDecimals);
return upscale(a, fromDecimals, toDecimals);
}
functionupscale(uint256 a,
uint8 fromDecimals,
uint8 toDecimals
) internalpurereturns (uint256) {
return a * (10** (toDecimals - fromDecimals));
}
functiondownscale(uint256 a,
uint8 fromDecimals,
uint8 toDecimals
) internalpurereturns (uint256) {
return a / (10** (fromDecimals - toDecimals));
}
functionupscale(int256 a,
uint8 fromDecimals,
uint8 toDecimals
) internalpurereturns (int256) {
return a *int256(10** (toDecimals - fromDecimals));
}
functiondownscale(int256 a,
uint8 fromDecimals,
uint8 toDecimals
) internalpurereturns (int256) {
return a /int256(10** (fromDecimals - toDecimals));
}
functionintPow(uint256 a, uint256 n) internalpurereturns (uint256) {
uint256 result = ONE;
for (uint256 i; i < n; ) {
result = mulDown(result, a);
unchecked {
++i;
}
}
return result;
}
functionabsSub(uint256 a, uint256 b) internalpurereturns (uint256) {
unchecked {
return a >= b ? a - b : b - a;
}
}
functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a >= b ? a : b;
}
functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a <= b ? a : b;
}
}