Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 16878791 | 603 days ago | Contract Creation | 0 ETH |
Cross-Chain Transactions
Loading...
Loading
Contract Name:
Liquidation
Compiler Version
v0.8.21+commit.d9974bed
Optimization Enabled:
Yes with 200 runs
Other Settings:
shanghai EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import { IonPool } from "./IonPool.sol";
import { WadRayMath, RAY } from "./libraries/math/WadRayMath.sol";
import { ReserveOracle } from "./oracles/reserve/ReserveOracle.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
/**
* @notice The liquidation module for the `IonPool`.
*
* Liquidations at Ion operate a little differently than traditional liquidation schemes. Usually, liquidations are a
* function of the market price of an asset. However, the liquidation module is function of the reserve oracle price
* which reflects a rate based on **beacon-chain balances**.
*
* There are 3 different types of liquidations that can take place:
* - Partial Liquidation: The liquidator pays off a portion of the debt and receives a portion of the collateral.
* - Dust Liquidation: The liquidator pays off all of the debt and receives some or all of the collateral.
* - Protocol Liquidation: The liquidator transfers the position's debt and collateral onto the protocol's balance
* sheet.
*
* NOTE: Protocol liqudations are unlikely to ever be executed since there is
* no profit incentive for a liquidator to do so. They exist solely as a
* fallback if a liquidator were to ever execute a liquidation onto a vault that
* had fallen into bad debt.
*
* @custom:security-contact [email protected]
*/
contract Liquidation {
using SafeERC20 for IERC20;
using WadRayMath for uint256;
using SafeCast for uint256;
error ExchangeRateCannotBeZero();
error VaultIsNotUnsafe(uint256 healthRatio);
error InvalidReserveOraclesLength(uint256 length);
error InvalidLiquidationThresholdsLength(uint256 length);
error InvalidMaxDiscountsLength(uint256 length);
error InvalidTargetHealth(uint256 targetHealth);
error InvalidLiquidationThreshold(uint256 liquidationThreshold);
error InvalidMaxDiscount(uint256 maxDiscount);
// --- Parameters ---
uint256 public immutable TARGET_HEALTH; // [ray] ex) 1.25e27 is 125%
uint256 public immutable BASE_DISCOUNT; // [ray] ex) 0.02e27 is 2%
uint256 public immutable MAX_DISCOUNT; // [ray] ex) 0.2e27 is 20%
// liquidation thresholds
uint256 public immutable LIQUIDATION_THRESHOLD; // [ray] liquidation threshold for ilkIndex 0
// exchange rates
address public immutable RESERVE_ORACLE; // reserve oracle providing exchange rate for ilkIndex 0
address public immutable PROTOCOL; // receives confiscated vault debt and collateral
IonPool public immutable POOL;
IERC20 public immutable UNDERLYING;
// --- Events ---
event Liquidate(
address indexed initiator, address indexed kpr, uint8 indexed ilkIndex, uint256 repay, uint256 gemOut
);
/**
* @notice Creates a new `Liquidation` instance.
* @param _ionPool The address of the `IonPool` contract.
* @param _protocol The address that will represent the protocol balance
* sheet (for protocol liquidation purposes).
* @param _reserveOracle Reserve oracle for the ilk.
* @param _liquidationThreshold Liquidation threshold for the ilk.
* @param _targetHealth The target health ratio for positions.
* @param _reserveFactor Base discount for collateral.
* @param _maxDiscount Max discount for the ilk.
*/
constructor(
address _ionPool,
address _protocol,
address _reserveOracle,
uint256 _liquidationThreshold,
uint256 _targetHealth,
uint256 _reserveFactor,
uint256 _maxDiscount
) {
IonPool ionPool_ = IonPool(_ionPool);
POOL = ionPool_;
PROTOCOL = _protocol;
if (_maxDiscount >= RAY) revert InvalidMaxDiscount(_maxDiscount);
if (_liquidationThreshold == 0) revert InvalidLiquidationThreshold(_liquidationThreshold);
// This invariant must hold otherwise all liquidations will revert
// when discount == configs.maxDiscount within the _getRepayAmt
// function.
if (_targetHealth < _liquidationThreshold.rayDivUp(RAY - _maxDiscount)) {
revert InvalidTargetHealth(_targetHealth);
}
if (_targetHealth < RAY) revert InvalidTargetHealth(_targetHealth);
TARGET_HEALTH = _targetHealth;
BASE_DISCOUNT = _reserveFactor;
MAX_DISCOUNT = _maxDiscount;
IERC20 underlying = ionPool_.underlying();
underlying.approve(address(ionPool_), type(uint256).max); // approve ionPool to transfer the UNDERLYING asset
UNDERLYING = underlying;
LIQUIDATION_THRESHOLD = _liquidationThreshold;
RESERVE_ORACLE = _reserveOracle;
}
struct Configs {
uint256 liquidationThreshold;
uint256 maxDiscount;
address reserveOracle;
}
/**
* @notice Returns the exchange rate, liquidation threshold, and max
* discount for the given ilk.
*/
function _getConfig() internal view returns (Configs memory configs) {
configs.reserveOracle = RESERVE_ORACLE;
configs.liquidationThreshold = LIQUIDATION_THRESHOLD;
configs.maxDiscount = MAX_DISCOUNT;
}
/**
* @notice If liquidation is possible, returns the amount of WETH necessary
* to liquidate a vault.
* @param ilkIndex The index of the ilk.
* @param vault The address of the vault.
* @return repay The amount of WETH necessary to liquidate the vault.
*/
function getRepayAmt(uint8 ilkIndex, address vault) public view returns (uint256 repay) {
Configs memory configs = _getConfig();
// exchangeRate is reported in uint72 in [wad], but should be converted to uint256 [ray]
uint256 exchangeRate = uint256(ReserveOracle(configs.reserveOracle).currentExchangeRate()).scaleUpToRay(18);
(uint256 collateral, uint256 normalizedDebt) = POOL.vault(ilkIndex, vault);
uint256 rate = POOL.rate(ilkIndex);
if (exchangeRate == 0) {
revert ExchangeRateCannotBeZero();
}
// collateralValue = collateral * exchangeRate * liquidationThreshold
// debtValue = normalizedDebt * rate
// healthRatio = collateralValue / debtValue
// collateralValue = [wad] * [ray] * [ray] / RAY = [rad]
// debtValue = [wad] * [ray] = [rad]
// healthRatio = [rad] * RAY / [rad] = [ray]
// round down in protocol favor
uint256 collateralValue = (collateral * exchangeRate).rayMulDown(configs.liquidationThreshold);
uint256 healthRatio = collateralValue.rayDivDown(normalizedDebt * rate); // round down in protocol favor
if (healthRatio >= RAY) {
revert VaultIsNotUnsafe(healthRatio);
}
uint256 discount = BASE_DISCOUNT + (RAY - healthRatio); // [ray] + ([ray] - [ray])
discount = discount <= configs.maxDiscount ? discount : configs.maxDiscount; // cap discount to maxDiscount
// favor
uint256 repayRad = _getRepayAmt(normalizedDebt * rate, collateralValue, configs.liquidationThreshold, discount);
if (repayRad > normalizedDebt * rate) return 0;
else if (normalizedDebt * rate - repayRad < POOL.dust(ilkIndex)) repayRad = normalizedDebt * rate;
return repayRad % RAY > 0 ? repayRad / RAY + 1 : repayRad / RAY;
}
/**
* @notice Internal helper function for calculating the repay amount.
* @param debtValue The total debt. [RAD]
* @param collateralValue Calculated with collateral * exchangeRate * liquidationThreshold. [RAD]
* @param liquidationThreshold Ratio at which liquidation can occur. [RAY]
* @param discount The discount from the exchange rate at which the collateral is sold. [RAY]
* @return repay The amount of WETH necessary to liquidate the vault. [RAD]
*/
function _getRepayAmt(
uint256 debtValue,
uint256 collateralValue,
uint256 liquidationThreshold,
uint256 discount
)
internal
view
returns (uint256 repay)
{
// repayNum = (targetHealth * totalDebt - collateral * exchangeRate * liquidationThreshold)
// repayDen = (targetHealth - (liquidationThreshold / (1 - discount)))
// repay = repayNum / repayDen
// Round up repay in protocol favor for safer post-liquidation position
// This will never underflow because at this point we know health ratio
// is less than 1, which means that collateralValue < debtValue.
uint256 repayNum = debtValue.rayMulUp(TARGET_HEALTH) - collateralValue; // [rad] - [rad] = [rad]
uint256 repayDen = TARGET_HEALTH - liquidationThreshold.rayDivUp(RAY - discount); // [ray]
repay = repayNum.rayDivUp(repayDen); // [rad] * RAY / [ray] = [rad]
}
struct LiquidateArgs {
uint256 repay;
uint256 gemOut;
uint256 dart;
uint256 fee;
uint256 price;
}
/**
* @notice Closes an unhealthy position on `IonPool`.
* @param ilkIndex The index of the collateral.
* @param vault The position to be liquidated.
* @param kpr Receiver of the collateral.
* @return repayAmount The amount of WETH paid to close the position.
* @return gemOut The amount of collateral received from the liquidation.
*/
function liquidate(
uint8 ilkIndex,
address vault,
address kpr
)
external
returns (uint256 repayAmount, uint256 gemOut)
{
LiquidateArgs memory liquidateArgs;
Configs memory configs = _getConfig();
// exchangeRate is reported in uint72 in [wad], but should be converted to uint256 [ray]
uint256 exchangeRate = ReserveOracle(configs.reserveOracle).currentExchangeRate().scaleUpToRay(18);
(uint256 collateral, uint256 normalizedDebt) = POOL.vault(ilkIndex, vault);
uint256 rate = POOL.rate(ilkIndex);
if (exchangeRate == 0) {
revert ExchangeRateCannotBeZero();
}
// collateralValue = collateral * exchangeRate * liquidationThreshold
// debtValue = normalizedDebt * rate
// healthRatio = collateralValue / debtValue
// collateralValue = [wad] * [ray] * [ray] / RAY = [rad]
// debtValue = [wad] * [ray] = [rad]
// healthRatio = [rad] * RAY / [rad] = [ray]
// round down in protocol favor
uint256 collateralValue = (collateral * exchangeRate).rayMulDown(configs.liquidationThreshold);
{
uint256 healthRatio = collateralValue.rayDivDown(normalizedDebt * rate); // round down in protocol favor
if (healthRatio >= RAY) {
revert VaultIsNotUnsafe(healthRatio);
}
uint256 discount = BASE_DISCOUNT + (RAY - healthRatio); // [ray] + ([ray] - [ray])
discount = discount <= configs.maxDiscount ? discount : configs.maxDiscount; // cap discount to maxDiscount
liquidateArgs.price = exchangeRate.rayMulUp(RAY - discount); // ETH price per LST, round up in protocol
// favor
liquidateArgs.repay =
_getRepayAmt(normalizedDebt * rate, collateralValue, configs.liquidationThreshold, discount);
}
// First branch: protocol liquidation
// if repay > total debt, more debt needs to be paid off than available to go back to target health
// Move exactly all collateral and debt to the protocol.
// Second branch: resulting debt is below dust
// There is enough collateral to cover the debt and go back to target health,
// but it would leave a debt amount less than dust.
// Force keeper to pay off all debt including dust and readjust the amount of collateral to sell.
// Resulting debt should always be zero.
// Third branch: partial liquidation to target health ratio
// There is enough collateral to be sold to pay off debt.
// Liquidator pays portion of the debt and receives collateral.
// The resulting health ratio should equal target health.
if (liquidateArgs.repay > normalizedDebt * rate) {
// [rad] > [rad]
liquidateArgs.dart = normalizedDebt; // [wad]
liquidateArgs.gemOut = collateral; // [wad]
POOL.confiscateVault(
ilkIndex, vault, PROTOCOL, PROTOCOL, -int256(liquidateArgs.gemOut), -int256(liquidateArgs.dart)
);
emit Liquidate(msg.sender, kpr, ilkIndex, liquidateArgs.dart, liquidateArgs.gemOut);
return (0, 0); // early return
} else if (normalizedDebt * rate - liquidateArgs.repay < POOL.dust(ilkIndex)) {
// [rad] - [rad] < [rad]
liquidateArgs.repay = normalizedDebt * rate; // bound repay to total debt
liquidateArgs.dart = normalizedDebt; // pay off all debt including dust
liquidateArgs.gemOut = normalizedDebt * rate / liquidateArgs.price; // round down in protocol favor
} else {
// if (normalizedDebt * rate - liquidateArgs.repay >= dust) do partial liquidation
// round up in protocol favor
liquidateArgs.dart = liquidateArgs.repay / rate; // [rad] / [ray] = [wad]
if (liquidateArgs.repay % rate > 0) ++liquidateArgs.dart; // round up in protocol favor
// round down in protocol favor
liquidateArgs.gemOut = liquidateArgs.repay / liquidateArgs.price; // readjust amount of collateral
liquidateArgs.repay = liquidateArgs.dart * rate; // 27 decimals precision loss on original repay
}
// below code is only reached for dust or partial liquidations
// exact amount to be transferred in `_transferWeth`
uint256 transferAmt = (liquidateArgs.repay / RAY);
if (liquidateArgs.repay % RAY > 0) ++transferAmt; // round up in protocol favor
// transfer WETH from keeper to this contract
UNDERLYING.safeTransferFrom(msg.sender, address(this), transferAmt);
// take the debt to pay off and the collateral to sell from the vault
// kpr gets the gemOut
POOL.confiscateVault(
ilkIndex, vault, kpr, address(this), -(liquidateArgs.gemOut.toInt256()), -(liquidateArgs.dart.toInt256())
);
// pay off the unbacked debt
POOL.repayBadDebt(address(this), liquidateArgs.repay);
emit Liquidate(msg.sender, kpr, ilkIndex, liquidateArgs.dart, liquidateArgs.gemOut);
return (liquidateArgs.repay, liquidateArgs.gemOut);
}
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.21;
import { Whitelist } from "./Whitelist.sol";
import { SpotOracle } from "./oracles/spot/SpotOracle.sol";
import { RewardToken } from "./token/RewardToken.sol";
import { InterestRate } from "./InterestRate.sol";
import { WadRayMath, RAY } from "./libraries/math/WadRayMath.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
/**
* @notice `IonPool` is the central contract of the Ion Protocol system. All
* other contracts in the system revolve around it. Directly interacting with
* `IonPool` may be unintuitive and it is recommended to interface with the
* protocol through Handler contracts for a more UX-friendly experience.
*
* @custom:security-contact [email protected]
*/
contract IonPool is PausableUpgradeable, RewardToken {
using SafeERC20 for IERC20;
using SafeCast for *;
using WadRayMath for *;
using Math for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
// --- Errors ---
error CeilingExceeded(uint256 newDebt, uint256 debtCeiling);
error UnsafePositionChange(uint256 newTotalDebtInVault, uint256 collateral, uint256 spot);
error UnsafePositionChangeWithoutConsent(uint8 ilkIndex, address user, address unconsentedOperator);
error GemTransferWithoutConsent(uint8 ilkIndex, address user, address unconsentedOperator);
error UseOfCollateralWithoutConsent(uint8 ilkIndex, address depositor, address unconsentedOperator);
error TakingWethWithoutConsent(address payer, address unconsentedOperator);
error VaultCannotBeDusty(uint256 amountLeft, uint256 dust);
error ArithmeticError();
error IlkAlreadyAdded(address ilkAddress);
error IlkNotInitialized(uint256 ilkIndex);
error DepositSurpassesSupplyCap(uint256 depositAmount, uint256 supplyCap);
error MaxIlksReached();
error InvalidIlkAddress();
error InvalidInterestRateModule(InterestRate invalidInterestRateModule);
error InvalidWhitelist();
// --- Events ---
event IlkInitialized(uint8 indexed ilkIndex, address indexed ilkAddress);
event IlkSpotUpdated(uint8 indexed ilkIndex, address newSpot);
event IlkDebtCeilingUpdated(uint8 indexed ilkIndex, uint256 newDebtCeiling);
event IlkDustUpdated(uint8 indexed ilkIndex, uint256 newDust);
event SupplyCapUpdated(uint256 newSupplyCap);
event InterestRateModuleUpdated(address newModule);
event WhitelistUpdated(address newWhitelist);
event AddOperator(address indexed user, address indexed operator);
event RemoveOperator(address indexed user, address indexed operator);
event MintAndBurnGem(uint8 indexed ilkIndex, address indexed usr, int256 wad);
event TransferGem(uint8 indexed ilkIndex, address indexed src, address indexed dst, uint256 wad);
event Supply(
address indexed user, address indexed underlyingFrom, uint256 amount, uint256 supplyFactor, uint256 newDebt
);
event Withdraw(address indexed user, address indexed target, uint256 amount, uint256 supplyFactor, uint256 newDebt);
event WithdrawCollateral(uint8 indexed ilkIndex, address indexed user, address indexed recipient, uint256 amount);
event DepositCollateral(uint8 indexed ilkIndex, address indexed user, address indexed depositor, uint256 amount);
event Borrow(
uint8 indexed ilkIndex,
address indexed user,
address indexed recipient,
uint256 amountOfNormalizedDebt,
uint256 ilkRate,
uint256 totalDebt
);
event Repay(
uint8 indexed ilkIndex,
address indexed user,
address indexed payer,
uint256 amountOfNormalizedDebt,
uint256 ilkRate,
uint256 totalDebt
);
event RepayBadDebt(address indexed user, address indexed payer, uint256 rad);
event ConfiscateVault(
uint8 indexed ilkIndex,
address indexed u,
address v,
address indexed w,
int256 changeInCollateral,
int256 changeInNormalizedDebt
);
bytes32 public constant GEM_JOIN_ROLE = keccak256("GEM_JOIN_ROLE");
bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE");
bytes32 public constant PAUSE_ROLE = keccak256("PAUSE_ROLE");
address private immutable ADDRESS_THIS = address(this);
// --- Modifiers ---
modifier onlyWhitelistedBorrowers(uint8 ilkIndex, address user, bytes32[] memory proof) {
IonPoolStorage storage $ = _getIonPoolStorage();
$.whitelist.isWhitelistedBorrower(ilkIndex, _msgSender(), user, proof);
_;
}
modifier onlyWhitelistedLenders(address user, bytes32[] memory proof) {
IonPoolStorage storage $ = _getIonPoolStorage();
$.whitelist.isWhitelistedLender(_msgSender(), user, proof);
_;
}
// --- Data ---
struct Ilk {
uint104 totalNormalizedDebt; // Total Normalised Debt [WAD]
uint104 rate; // Accumulated Rates [RAY]
uint48 lastRateUpdate; // block.timestamp of last update; overflows in 800_000 years
SpotOracle spot; // Oracle that provides price with safety margin
uint256 debtCeiling; // Debt Ceiling [RAD]
uint256 dust; // Vault Debt Floor [RAD]
}
struct Vault {
uint256 collateral; // Locked Collateral [WAD]
uint256 normalizedDebt; // Normalised Debt [WAD]
}
/// @custom:storage-location erc7201:ion.storage.IonPool
struct IonPoolStorage {
Ilk[] ilks;
// remove() should never be called, it will mess up the ordering
EnumerableSet.AddressSet ilkAddresses;
mapping(uint256 ilkIndex => mapping(address user => Vault)) vaults;
mapping(uint256 ilkIndex => mapping(address user => uint256)) gem; // [WAD]
mapping(address unbackedDebtor => uint256) unbackedDebt; // [RAD]
mapping(address user => mapping(address operator => uint256)) isOperator;
uint256 debt; // Total Debt [RAD]
uint256 liquidity; // liquidity in pool [WAD]
uint256 supplyCap; // [WAD]
uint256 totalUnbackedDebt; // Total Unbacked Underlying [RAD]
InterestRate interestRateModule;
Whitelist whitelist;
}
// keccak256(abi.encode(uint256(keccak256("ion.storage.IonPool")) - 1)) & ~bytes32(uint256(0xff))
// solhint-disable-next-line
bytes32 private constant IonPoolStorageLocation = 0xceba3d526b4d5afd91d1b752bf1fd37917c20a6daf576bcb41dd1c57c1f67e00;
function _getIonPoolStorage() internal pure returns (IonPoolStorage storage $) {
assembly {
$.slot := IonPoolStorageLocation
}
}
constructor() {
_disableInitializers();
}
function initialize(
address _underlying,
address _treasury,
uint8 decimals_,
string memory name_,
string memory symbol_,
address initialDefaultAdmin,
InterestRate _interestRateModule,
Whitelist _whitelist
)
external
initializer
{
__AccessControlDefaultAdminRules_init(0, initialDefaultAdmin);
RewardToken._initialize(_underlying, _treasury, decimals_, name_, symbol_);
_grantRole(ION, initialDefaultAdmin);
IonPoolStorage storage $ = _getIonPoolStorage();
$.interestRateModule = _interestRateModule;
$.whitelist = _whitelist;
emit InterestRateModuleUpdated(address(_interestRateModule));
emit WhitelistUpdated(address(_whitelist));
}
// --- Administration ---
/**
* @notice Initializes a market with a new collateral type.
* @dev This function and the entire protocol as a whole operates under the
* assumption that there will never be more than 256 collaterals.
* @param ilkAddress address of the ERC-20 collateral.
*/
function initializeIlk(address ilkAddress) external onlyRole(ION) {
IonPoolStorage storage $ = _getIonPoolStorage();
if (ilkAddress == address(0)) revert InvalidIlkAddress();
if (!$.ilkAddresses.add(ilkAddress)) revert IlkAlreadyAdded(ilkAddress);
uint256 ilksLength = $.ilks.length;
// Explicitly enforce the max number of collaterals
if (ilksLength >= uint256(type(uint8).max) + 1) revert MaxIlksReached();
// Unsafe cast OK since we don't plan on having more than 256
// collaterals
uint8 ilkIndex = uint8(ilksLength);
Ilk memory newIlk;
$.ilks.push(newIlk);
Ilk storage ilk = $.ilks[ilkIndex];
ilk.rate = uint104(RAY);
// Unsafe cast OK
ilk.lastRateUpdate = uint48(block.timestamp);
emit IlkInitialized(ilkIndex, ilkAddress);
}
/**
* @dev Updates the spot oracle for a given collateral.
* @param ilkIndex index of the collateral.
* @param newSpot address of the new spot oracle.
*/
function updateIlkSpot(uint8 ilkIndex, SpotOracle newSpot) external onlyRole(ION) {
IonPoolStorage storage $ = _getIonPoolStorage();
$.ilks[ilkIndex].spot = newSpot;
emit IlkSpotUpdated(ilkIndex, address(newSpot));
}
/**
* @notice A market can be sunset by setting the debt ceiling to 0. It would
* still be possible to repay debt but creating new debt would not be
* possible.
* @dev Updates the debt ceiling for a given collateral.
* @param ilkIndex index of the collateral.
* @param newCeiling new debt ceiling.
*/
function updateIlkDebtCeiling(uint8 ilkIndex, uint256 newCeiling) external onlyRole(ION) {
IonPoolStorage storage $ = _getIonPoolStorage();
$.ilks[ilkIndex].debtCeiling = newCeiling;
emit IlkDebtCeilingUpdated(ilkIndex, newCeiling);
}
/**
* @notice When increasing the `dust`, it is possible that some vaults will
* be dusty after the update. However, changes to the vault position from
* there will require that the vault be non-dusty (either by repaying all
* debt or increasing debt beyond the `dust`).
* @dev Updates the dust amount for a given collateral.
* @param ilkIndex index of the collateral.
* @param newDust new dust
*/
function updateIlkDust(uint8 ilkIndex, uint256 newDust) external onlyRole(ION) {
IonPoolStorage storage $ = _getIonPoolStorage();
$.ilks[ilkIndex].dust = newDust;
emit IlkDustUpdated(ilkIndex, newDust);
}
/**
* @notice Reducing the supply cap will not affect existing deposits.
* However, if it is below the `totalSupply`, then no new deposits will be
* allowed until the `totalSupply` is below the new `supplyCap`.
* @dev Updates the supply cap.
* @param newSupplyCap new supply cap.
*/
function updateSupplyCap(uint256 newSupplyCap) external onlyRole(ION) {
IonPoolStorage storage $ = _getIonPoolStorage();
$.supplyCap = newSupplyCap;
emit SupplyCapUpdated(newSupplyCap);
}
/**
* @dev Updates the interest rate module. There is a check to ensure that
* `collateralCount()` on the new interest rate module match the current
* number of collaterals in the pool.
* @param _interestRateModule new interest rate module.
*/
function updateInterestRateModule(InterestRate _interestRateModule) external onlyRole(ION) {
if (address(_interestRateModule) == address(0)) revert InvalidInterestRateModule(_interestRateModule);
IonPoolStorage storage $ = _getIonPoolStorage();
// Sanity check
if (_interestRateModule.COLLATERAL_COUNT() != $.ilks.length) {
revert InvalidInterestRateModule(_interestRateModule);
}
$.interestRateModule = _interestRateModule;
emit InterestRateModuleUpdated(address(_interestRateModule));
}
/**
* @dev Updates the whitelist.
* @param _whitelist new whitelist address.
*/
function updateWhitelist(Whitelist _whitelist) external onlyRole(ION) {
if (address(_whitelist) == address(0)) revert InvalidWhitelist();
IonPoolStorage storage $ = _getIonPoolStorage();
$.whitelist = _whitelist;
emit WhitelistUpdated(address(_whitelist));
}
/**
* @dev Pause actions but accrue interest as well.
*
* Under certain protocol conditions, we want to be able to pause the
* protocol automatically through monitoring systems. So we want to be able
* to grant the PAUSE_ROLE to those private keys. In the case of a
* compromised private key, we can revoke the PAUSE_ROLE from that private
* key and grant it to a new private key. Unpausing will remain a multisig
* operation.
*/
function pause() external onlyRole(PAUSE_ROLE) {
_accrueInterest();
_pause();
}
/**
* @dev Unpause actions but this will also update the `lastRateUpdate` to
* the unpause transaction timestamp. This essentially allows for a pausing
* and unpausing of the accrual of interest.
*/
function unpause() external onlyRole(ION) {
_unpause();
IonPoolStorage storage $ = _getIonPoolStorage();
uint256 ilksLength = $.ilks.length;
for (uint256 i = 0; i < ilksLength;) {
// Unsafe cast OK
$.ilks[i].lastRateUpdate = uint48(block.timestamp);
// forgefmt: disable-next-line
unchecked { ++i; }
}
}
// --- Interest Calculations ---
/**
* @dev Updates accumulators for all `ilk`s based on current interest rates.
* @return newTotalDebt the new total debt after interest accrual
*/
function accrueInterest() external whenNotPaused returns (uint256 newTotalDebt) {
return _accrueInterest();
}
function _accrueInterest() internal returns (uint256 newTotalDebt) {
IonPoolStorage storage $ = _getIonPoolStorage();
uint256 totalEthSupply = totalSupplyUnaccrued();
uint256 totalSupplyFactorIncrease;
uint256 totalTreasuryMintAmount;
uint256 totalDebtIncrease;
uint256 ilksLength = $.ilks.length;
for (uint8 i = 0; i < ilksLength;) {
(
uint256 supplyFactorIncrease,
uint256 treasuryMintAmount,
uint104 newRateIncrease,
uint256 newDebtIncrease,
uint48 timestampIncrease
) = _calculateRewardAndDebtDistributionForIlk(i, totalEthSupply);
if (timestampIncrease > 0) {
Ilk storage ilk = $.ilks[i];
ilk.rate += newRateIncrease;
ilk.lastRateUpdate += timestampIncrease;
totalDebtIncrease += newDebtIncrease;
totalSupplyFactorIncrease += supplyFactorIncrease;
totalTreasuryMintAmount += treasuryMintAmount;
}
// forgefmt: disable-next-line
unchecked { ++i; }
}
newTotalDebt = $.debt + totalDebtIncrease;
$.debt = newTotalDebt;
_setSupplyFactor(supplyFactorUnaccrued() + totalSupplyFactorIncrease);
_mintToTreasury(totalTreasuryMintAmount);
}
function calculateRewardAndDebtDistribution()
public
view
override
returns (
uint256 totalSupplyFactorIncrease,
uint256 totalTreasuryMintAmount,
uint104[] memory rateIncreases,
uint256 totalDebtIncrease,
uint48[] memory timestampIncreases
)
{
IonPoolStorage storage $ = _getIonPoolStorage();
uint256 ilksLength = $.ilks.length;
rateIncreases = new uint104[](ilksLength);
timestampIncreases = new uint48[](ilksLength);
uint256 totalEthSupply = totalSupplyUnaccrued();
for (uint8 i = 0; i < ilksLength;) {
(
uint256 supplyFactorIncrease,
uint256 treasuryMintAmount,
uint104 newRateIncrease,
uint256 newDebtIncrease,
uint48 timestampIncrease
) = _calculateRewardAndDebtDistributionForIlk(i, totalEthSupply);
if (timestampIncrease > 0) {
rateIncreases[i] = newRateIncrease;
timestampIncreases[i] = timestampIncrease;
totalDebtIncrease += newDebtIncrease;
totalSupplyFactorIncrease += supplyFactorIncrease;
totalTreasuryMintAmount += treasuryMintAmount;
}
// forgefmt: disable-next-line
unchecked { ++i; }
}
}
/**
* @notice This is primarily for simulation purposes to see how an
* individual ilk's state will change after an accrual.
* @param ilkIndex index of the collateral.
* @return newRateIncrease the rate increase for the ilk.
* @return timestampIncrease the timestamp increase for the ilk.
*/
function calculateRewardAndDebtDistributionForIlk(uint8 ilkIndex)
public
view
returns (uint104 newRateIncrease, uint48 timestampIncrease)
{
(,, newRateIncrease,, timestampIncrease) =
_calculateRewardAndDebtDistributionForIlk(ilkIndex, totalSupplyUnaccrued());
}
function _calculateRewardAndDebtDistributionForIlk(
uint8 ilkIndex,
uint256 totalEthSupply
)
internal
view
returns (
uint256 supplyFactorIncrease,
uint256 treasuryMintAmount,
uint104 newRateIncrease,
uint256 newDebtIncrease,
uint48 timestampIncrease
)
{
IonPoolStorage storage $ = _getIonPoolStorage();
Ilk storage ilk = $.ilks[ilkIndex];
uint256 _totalNormalizedDebt = ilk.totalNormalizedDebt;
// Because all interest that would have accrued during a pause is
// cancelled upon `unpause`, we return zero interest while markets are
// paused.
if (_totalNormalizedDebt == 0 || block.timestamp == ilk.lastRateUpdate || paused()) {
// Unsafe cast OK
// block.timestamp - ilk.lastRateUpdate will almost always be 0
// here. The exception is on first borrow.
return (0, 0, 0, 0, uint48(block.timestamp - ilk.lastRateUpdate));
}
uint256 totalDebt = _totalNormalizedDebt * ilk.rate; // [WAD] * [RAY] = [RAD]
(uint256 borrowRate, uint256 reserveFactor) =
$.interestRateModule.calculateInterestRate(ilkIndex, totalDebt, totalEthSupply);
// Unsafe cast OK
timestampIncrease = uint48(block.timestamp) - ilk.lastRateUpdate;
if (borrowRate == 0) return (0, 0, 0, 0, timestampIncrease);
// Calculates borrowRate ^ (time) and returns the result with RAY precision
uint256 borrowRateExpT = _rpow(borrowRate + RAY, timestampIncrease, RAY);
// Debt distribution
// This form of rate accrual is much safer than distributing the new
// debt increase to the total debt since low debt amounts won't cause
// rounding errors to sky rocket the rate. This form of accrual is still
// subject to rate inflation, however, it would only be from an
// extremely high borrow rate rather than being a function of the
// current total debt in the system. This is very relevant for
// sunsetting markets, where the goal will be to reduce the total debt
// to 0.
newRateIncrease = ilk.rate.rayMulUp(borrowRateExpT - RAY).toUint104(); // [RAY]
newDebtIncrease = _totalNormalizedDebt * newRateIncrease; // [RAD]
// Income distribution
uint256 _normalizedTotalSupply = normalizedTotalSupplyUnaccrued(); // [WAD]
// If there is no supply, then nothing is being lent out.
supplyFactorIncrease = _normalizedTotalSupply == 0
? 0
: newDebtIncrease.mulDiv(RAY - reserveFactor, _normalizedTotalSupply.scaleUpToRad(18)); // [RAD] * [RAY] / [RAD]
// = [RAY]
treasuryMintAmount = newDebtIncrease.mulDiv(reserveFactor, 1e54); // [RAD] * [RAY] / 1e54 = [WAD]
}
// --- Lender Operations ---
/**
* @dev Allows lenders to redeem their interest-bearing position for the
* underlying asset. It is possible that dust amounts more of the position
* are burned than the underlying received due to rounding.
* @param receiverOfUnderlying the address to which the redeemed underlying
* asset should be sent to.
* @param amount of underlying to reedeem for.
*/
function withdraw(address receiverOfUnderlying, uint256 amount) external whenNotPaused {
uint256 newTotalDebt = _accrueInterest();
IonPoolStorage storage $ = _getIonPoolStorage();
$.liquidity -= amount;
uint256 _supplyFactor =
_burn({ user: _msgSender(), receiverOfUnderlying: receiverOfUnderlying, amount: amount });
emit Withdraw(_msgSender(), receiverOfUnderlying, amount, _supplyFactor, newTotalDebt);
}
/**
* @dev Allows lenders to deposit their underlying asset into the pool and
* earn interest on it.
* @param user the address to receive credit for the position.
* @param amount of underlying asset to use to create the position.
* @param proof merkle proof that the user is whitelisted.
*/
function supply(
address user,
uint256 amount,
bytes32[] calldata proof
)
external
whenNotPaused
onlyWhitelistedLenders(user, proof)
{
uint256 newTotalDebt = _accrueInterest();
IonPoolStorage storage $ = _getIonPoolStorage();
$.liquidity += amount;
uint256 _supplyFactor = _mint({ user: user, senderOfUnderlying: _msgSender(), amount: amount });
uint256 _supplyCap = $.supplyCap;
if (totalSupply() > _supplyCap) revert DepositSurpassesSupplyCap(amount, _supplyCap);
emit Supply(user, _msgSender(), amount, _supplyFactor, newTotalDebt);
}
// --- Borrower Operations ---
/**
* @dev Allows a borrower to create debt in a position.
* @param ilkIndex index of the collateral.
* @param user to create the position for.
* @param recipient to receive the borrowed funds
* @param amountOfNormalizedDebt to create.
* @param proof merkle proof that the user is whitelist.
*/
function borrow(
uint8 ilkIndex,
address user,
address recipient,
uint256 amountOfNormalizedDebt,
bytes32[] memory proof
)
external
whenNotPaused
onlyWhitelistedBorrowers(ilkIndex, user, proof)
{
_accrueInterest();
(uint104 ilkRate, uint256 newDebt) =
_modifyPosition(ilkIndex, user, address(0), recipient, 0, amountOfNormalizedDebt.toInt256());
emit Borrow(ilkIndex, user, recipient, amountOfNormalizedDebt, ilkRate, newDebt);
}
/**
* @dev Allows a borrower to repay debt in a position.
* @param ilkIndex index of the collateral.
* @param user to repay the debt for.
* @param payer to source the funds from.
* @param amountOfNormalizedDebt to repay.
*/
function repay(
uint8 ilkIndex,
address user,
address payer,
uint256 amountOfNormalizedDebt
)
external
whenNotPaused
{
_accrueInterest();
(uint104 ilkRate, uint256 newDebt) =
_modifyPosition(ilkIndex, user, address(0), payer, 0, -(amountOfNormalizedDebt.toInt256()));
emit Repay(ilkIndex, user, payer, amountOfNormalizedDebt, ilkRate, newDebt);
}
/**
* @dev Moves collateral from internal `vault.collateral` balances to `gem`
* @param ilkIndex index of the collateral.
* @param user to withdraw the collateral for.
* @param recipient to receive the collateral.
* @param amount to withdraw.
*/
function withdrawCollateral(
uint8 ilkIndex,
address user,
address recipient,
uint256 amount
)
external
whenNotPaused
{
_accrueInterest();
_modifyPosition(ilkIndex, user, recipient, address(0), -(amount.toInt256()), 0);
emit WithdrawCollateral(ilkIndex, user, recipient, amount);
}
/**
* @dev Moves collateral from `gem` balances to internal `vault.collateral`
* @param ilkIndex index of the collateral.
* @param user to deposit the collateral for.
* @param depositor to deposit the collateral from.
* @param amount to deposit.
* @param proof merkle proof that the user is whitelisted.
*/
function depositCollateral(
uint8 ilkIndex,
address user,
address depositor,
uint256 amount,
bytes32[] calldata proof
)
external
whenNotPaused
onlyWhitelistedBorrowers(ilkIndex, user, proof)
{
_accrueInterest();
_modifyPosition(ilkIndex, user, depositor, address(0), amount.toInt256(), 0);
emit DepositCollateral(ilkIndex, user, depositor, amount);
}
// --- CDP Manipulation ---
function _modifyPosition(
uint8 ilkIndex,
address u,
address v,
address w,
int256 changeInCollateral,
int256 changeInNormalizedDebt
)
internal
returns (uint104 ilkRate, uint256 newTotalDebt)
{
IonPoolStorage storage $ = _getIonPoolStorage();
ilkRate = $.ilks[ilkIndex].rate;
// ilk has been initialised
if (ilkRate == 0) revert IlkNotInitialized(ilkIndex);
Vault memory _vault = $.vaults[ilkIndex][u];
_vault.collateral = _add(_vault.collateral, changeInCollateral);
_vault.normalizedDebt = _add(_vault.normalizedDebt, changeInNormalizedDebt);
uint104 _totalNormalizedDebt = _add($.ilks[ilkIndex].totalNormalizedDebt, changeInNormalizedDebt).toUint104();
// Prevent stack too deep
{
uint256 newTotalDebtInVault = ilkRate * _vault.normalizedDebt;
// either debt has decreased, or debt ceilings are not exceeded
if (
both(
changeInNormalizedDebt > 0,
uint256(_totalNormalizedDebt) * uint256(ilkRate) > $.ilks[ilkIndex].debtCeiling
)
) {
revert CeilingExceeded(uint256(_totalNormalizedDebt) * uint256(ilkRate), $.ilks[ilkIndex].debtCeiling);
}
uint256 ilkSpot = $.ilks[ilkIndex].spot.getSpot();
// vault is either less risky than before, or it is safe
if (
both(
either(changeInNormalizedDebt > 0, changeInCollateral < 0),
newTotalDebtInVault > _vault.collateral * ilkSpot
)
) revert UnsafePositionChange(newTotalDebtInVault, _vault.collateral, ilkSpot);
// vault is either more safe, or the owner consents
if (both(either(changeInNormalizedDebt > 0, changeInCollateral < 0), !isAllowed(u, _msgSender()))) {
revert UnsafePositionChangeWithoutConsent(ilkIndex, u, _msgSender());
}
// collateral src consents
if (both(changeInCollateral > 0, !isAllowed(v, _msgSender()))) {
revert UseOfCollateralWithoutConsent(ilkIndex, v, _msgSender());
}
// debt dst consents
// Since changeInDebt is no longer being deducted in the form of
// internal accounting but rather directly in the erc20 WETH form, this
// contract must also have an approved role for the debt dst address on
// th erc20 WETH contract. Or else, the transfer will fail.
if (both(changeInNormalizedDebt < 0, !isAllowed(w, _msgSender()))) {
revert TakingWethWithoutConsent(w, _msgSender());
}
// vault has no debt, or a non-dusty amount
if (both(_vault.normalizedDebt != 0, newTotalDebtInVault < $.ilks[ilkIndex].dust)) {
revert VaultCannotBeDusty(newTotalDebtInVault, $.ilks[ilkIndex].dust);
}
}
int256 changeInDebt = ilkRate.toInt256() * changeInNormalizedDebt;
$.gem[ilkIndex][v] = _sub($.gem[ilkIndex][v], changeInCollateral);
$.vaults[ilkIndex][u] = _vault;
$.ilks[ilkIndex].totalNormalizedDebt = _totalNormalizedDebt;
newTotalDebt = _add($.debt, changeInDebt);
$.debt = newTotalDebt;
// If changeInDebt < 0, it is a repayment and WETH is being transferred
// into the protocol
_transferWeth(w, changeInDebt);
}
// --- Settlement ---
/**
* @dev To be used by protocol to settle bad debt using reserves
* NOTE: Can pay another user's bad debt with the sender's asset
* @param user the address that owns the bad debt being paid off
* @param rad amount of debt to be repaid (45 decimals)
*/
function repayBadDebt(address user, uint256 rad) external whenNotPaused {
IonPoolStorage storage $ = _getIonPoolStorage();
$.unbackedDebt[user] -= rad;
$.totalUnbackedDebt -= rad;
$.debt -= rad;
// Must be negative since it is a repayment
_transferWeth(_msgSender(), -(rad.toInt256()));
emit RepayBadDebt(user, _msgSender(), rad);
}
// --- Helpers ---
/**
* @dev Helper function to deal with borrowing and repaying debt. A positive
* amount is a borrow while negative amount is a repayment
* @param user receiver if transfer to, or sender if transfer from
* @param amount amount to transfer [RAD]
*/
function _transferWeth(address user, int256 amount) internal {
if (amount == 0) return;
IonPoolStorage storage $ = _getIonPoolStorage();
if (amount < 0) {
uint256 amountUint = uint256(-amount);
uint256 amountWad = amountUint / RAY;
if (amountUint % RAY > 0) ++amountWad;
$.liquidity += amountWad;
underlying().safeTransferFrom(user, address(this), amountWad);
} else {
// Round down in protocol's favor
uint256 amountWad = uint256(amount) / RAY;
$.liquidity -= amountWad;
underlying().safeTransfer(user, amountWad);
}
}
// --- CDP Confiscation ---
/**
* @dev This function foregoes pausability for pausability at the
* liquidation module layer
* @param ilkIndex index of the collateral.
* @param u user to confiscate the vault from.
* @param v address to either credit `gem` to or deduct `gem` from
* @param changeInCollateral collateral to add or remove from the vault
* @param changeInNormalizedDebt debt to add or remove from the vault
*/
function confiscateVault(
uint8 ilkIndex,
address u,
address v,
address w,
int256 changeInCollateral,
int256 changeInNormalizedDebt
)
external
whenNotPaused
onlyRole(LIQUIDATOR_ROLE)
{
_accrueInterest();
IonPoolStorage storage $ = _getIonPoolStorage();
Vault storage _vault = $.vaults[ilkIndex][u];
Ilk storage ilk = $.ilks[ilkIndex];
uint104 ilkRate = ilk.rate;
_vault.collateral = _add(_vault.collateral, changeInCollateral);
_vault.normalizedDebt = _add(_vault.normalizedDebt, changeInNormalizedDebt);
ilk.totalNormalizedDebt = _add(uint256(ilk.totalNormalizedDebt), changeInNormalizedDebt).toUint104();
// Unsafe cast OK since we know that ilkRate is less than 2^104
int256 changeInDebt = int256(uint256(ilkRate)) * changeInNormalizedDebt;
$.gem[ilkIndex][v] = _sub($.gem[ilkIndex][v], changeInCollateral);
$.unbackedDebt[w] = _sub($.unbackedDebt[w], changeInDebt);
$.totalUnbackedDebt = _sub($.totalUnbackedDebt, changeInDebt);
emit ConfiscateVault(ilkIndex, u, v, w, changeInCollateral, changeInNormalizedDebt);
}
// --- Fungibility ---
/**
* @dev To be called by GemJoin contracts. After a user deposits collateral, credit the user with collateral
* internally
* @param ilkIndex collateral
* @param usr user
* @param wad amount to add or remove
*/
function mintAndBurnGem(uint8 ilkIndex, address usr, int256 wad) external onlyRole(GEM_JOIN_ROLE) whenNotPaused {
IonPoolStorage storage $ = _getIonPoolStorage();
$.gem[ilkIndex][usr] = _add($.gem[ilkIndex][usr], wad);
emit MintAndBurnGem(ilkIndex, usr, wad);
}
/**
* @dev Transfer gem across the internal accounting of the pool
* @param ilkIndex index of the collateral
* @param src source of the gem
* @param dst destination of the gem
* @param wad amount of gem
*/
function transferGem(uint8 ilkIndex, address src, address dst, uint256 wad) external whenNotPaused {
if (!isAllowed(src, _msgSender())) revert GemTransferWithoutConsent(ilkIndex, src, _msgSender());
IonPoolStorage storage $ = _getIonPoolStorage();
$.gem[ilkIndex][src] -= wad;
$.gem[ilkIndex][dst] += wad;
emit TransferGem(ilkIndex, src, dst, wad);
}
// --- Getters ---
/**
* @return The address of the collateral at index `ilkIndex`.
*/
function getIlkAddress(uint256 ilkIndex) external view returns (address) {
IonPoolStorage storage $ = _getIonPoolStorage();
return $.ilkAddresses.at(ilkIndex);
}
/**
* @return The rate (debt accumulator) for collateral with index `ilkIndex`.
*/
function rate(uint8 ilkIndex) external view returns (uint256) {
IonPoolStorage storage $ = _getIonPoolStorage();
(uint256 newRateIncrease,) = calculateRewardAndDebtDistributionForIlk(ilkIndex);
return $.ilks[ilkIndex].rate + newRateIncrease;
}
/**
* @return dust amount for collateral with index `ilkIndex`.
*/
function dust(uint8 ilkIndex) external view returns (uint256) {
IonPoolStorage storage $ = _getIonPoolStorage();
return $.ilks[ilkIndex].dust;
}
/**
* @return The amount of collateral `user` has for collateral with index `ilkIndex`.
*/
function collateral(uint8 ilkIndex, address user) external view returns (uint256) {
IonPoolStorage storage $ = _getIonPoolStorage();
return $.vaults[ilkIndex][user].collateral;
}
/**
* @return The amount of normalized debt `user` has for collateral with index `ilkIndex`.
*/
function normalizedDebt(uint8 ilkIndex, address user) external view returns (uint256) {
IonPoolStorage storage $ = _getIonPoolStorage();
return $.vaults[ilkIndex][user].normalizedDebt;
}
/**
* @return All data within vault for `user` with index `ilkIndex`.
*/
function vault(uint8 ilkIndex, address user) external view returns (uint256, uint256) {
IonPoolStorage storage $ = _getIonPoolStorage();
return ($.vaults[ilkIndex][user].collateral, $.vaults[ilkIndex][user].normalizedDebt);
}
/**
* @return Whether or not `operator` has permission to make unsafe changes
* to `user`'s positions.
*/
function isAllowed(address user, address operator) public view returns (bool) {
IonPoolStorage storage $ = _getIonPoolStorage();
return either(user == operator, $.isOperator[user][operator] == 1);
}
/**
* @dev Gets the current borrow rate for borrowing against a given collateral.
*/
function getCurrentBorrowRate(uint8 ilkIndex) external view returns (uint256 borrowRate, uint256 reserveFactor) {
IonPoolStorage storage $ = _getIonPoolStorage();
uint256 totalEthSupply = totalSupplyUnaccrued();
uint256 _totalNormalizedDebt = $.ilks[ilkIndex].totalNormalizedDebt;
uint256 _rate = $.ilks[ilkIndex].rate;
uint256 totalDebt = _totalNormalizedDebt * _rate; // [WAD] * [RAY] / [WAD] = [RAY]
(borrowRate, reserveFactor) = $.interestRateModule.calculateInterestRate(ilkIndex, totalDebt, totalEthSupply);
borrowRate += RAY;
}
function extsload(bytes32 slot) external view returns (bytes32 value) {
assembly {
value := sload(slot)
}
}
/**
* @dev Address of the implementation. This is stored immutably on the
* implementation so that it can be read by the proxy.
*/
function implementation() external view returns (address) {
return ADDRESS_THIS;
}
// --- Auth ---
/**
* @dev Allows an `operator` to make unsafe changes to `_msgSender()`s
* positions.
*/
function addOperator(address operator) external {
IonPoolStorage storage $ = _getIonPoolStorage();
$.isOperator[_msgSender()][operator] = 1;
emit AddOperator(_msgSender(), operator);
}
/**
* @dev Disallows an `operator` to make unsafe changes to `_msgSender()`s
* positions.
*/
function removeOperator(address operator) external {
IonPoolStorage storage $ = _getIonPoolStorage();
$.isOperator[_msgSender()][operator] = 0;
emit RemoveOperator(_msgSender(), operator);
}
// --- Math ---
function _add(uint256 x, int256 y) internal pure returns (uint256 z) {
// Overflow desirable
unchecked {
z = x + uint256(y);
}
if (y < 0 && z > x) revert ArithmeticError();
if (y > 0 && z < x) revert ArithmeticError();
}
function _sub(uint256 x, int256 y) internal pure returns (uint256 z) {
// Underflow desirable
unchecked {
z = x - uint256(y);
}
if (y > 0 && z > x) revert ArithmeticError();
if (y < 0 && z < x) revert ArithmeticError();
}
/**
* @dev x and the returned value are to be interpreted as fixed-point
* integers with scaling factor b. For example, if b == 100, this specifies
* two decimal digits of precision and the normal decimal value 2.1 would be
* represented as 210; rpow(210, 2, 100) returns 441 (the two-decimal digit
* fixed-point representation of 2.1^2 = 4.41) (From MCD docs)
* @param x base
* @param n exponent
* @param b scaling factor
*/
function _rpow(uint256 x, uint256 n, uint256 b) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 { z := b }
default { z := 0 }
}
default {
switch mod(n, 2)
case 0 { z := b }
default { z := x }
let half := div(b, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n, 2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0, 0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0, 0) }
x := div(xxRound, b)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0, 0) }
z := div(zxRound, b)
}
}
}
}
}
// --- Boolean ---
function either(bool x, bool y) internal pure returns (bool z) {
assembly {
z := or(x, y)
}
}
function both(bool x, bool y) internal pure returns (bool z) {
assembly {
z := and(x, y)
}
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
uint256 constant WAD = 1e18;
uint256 constant RAY = 1e27;
uint256 constant RAD = 1e45;
/**
* @title WadRayMath
*
* @notice This library provides mul/div[up/down] functionality for WAD, RAY and
* RAD with phantom overflow protection as well as scale[up/down] functionality
* for WAD, RAY and RAD.
*
* @custom:security-contact [email protected]
*/
library WadRayMath {
using Math for uint256;
error NotScalingUp(uint256 from, uint256 to);
error NotScalingDown(uint256 from, uint256 to);
/**
* @notice Multiplies two WAD numbers and returns the result as a WAD
* rounding the result down.
* @param a Multiplicand.
* @param b Multiplier.
*/
function wadMulDown(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(b, WAD);
}
/**
* @notice Multiplies two WAD numbers and returns the result as a WAD
* rounding the result up.
* @param a Multiplicand.
* @param b Multiplier.
*/
function wadMulUp(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(b, WAD, Math.Rounding.Ceil);
}
/**
* @notice Divides two WAD numbers and returns the result as a WAD rounding
* the result down.
* @param a Dividend.
* @param b Divisor.
*/
function wadDivDown(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(WAD, b);
}
/**
* @notice Divides two WAD numbers and returns the result as a WAD rounding
* the result up.
* @param a Dividend.
* @param b Divisor.
*/
function wadDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(WAD, b, Math.Rounding.Ceil);
}
/**
* @notice Multiplies two RAY numbers and returns the result as a RAY
* rounding the result down.
* @param a Multiplicand
* @param b Multiplier
*/
function rayMulDown(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(b, RAY);
}
/**
* @notice Multiplies two RAY numbers and returns the result as a RAY
* rounding the result up.
* @param a Multiplicand
* @param b Multiplier
*/
function rayMulUp(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(b, RAY, Math.Rounding.Ceil);
}
/**
* @notice Divides two RAY numbers and returns the result as a RAY
* rounding the result down.
* @param a Dividend
* @param b Divisor
*/
function rayDivDown(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(RAY, b);
}
/**
* @notice Divides two RAY numbers and returns the result as a RAY
* rounding the result up.
* @param a Dividend
* @param b Divisor
*/
function rayDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(RAY, b, Math.Rounding.Ceil);
}
/**
* @notice Multiplies two RAD numbers and returns the result as a RAD
* rounding the result down.
* @param a Multiplicand
* @param b Multiplier
*/
function radMulDown(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(b, RAD);
}
/**
* @notice Multiplies two RAD numbers and returns the result as a RAD
* rounding the result up.
* @param a Multiplicand
* @param b Multiplier
*/
function radMulUp(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(b, RAD, Math.Rounding.Ceil);
}
/**
* @notice Divides two RAD numbers and returns the result as a RAD rounding
* the result down.
* @param a Dividend
* @param b Divisor
*/
function radDivDown(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(RAD, b);
}
/**
* @notice Divides two RAD numbers and returns the result as a RAD rounding
* the result up.
* @param a Dividend
* @param b Divisor
*/
function radDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mulDiv(RAD, b, Math.Rounding.Ceil);
}
// --- Scalers ---
/**
* @notice Scales a value up from WAD. NOTE: The `scale` value must be
* less than 18.
* @param value to scale up.
* @param scale of the returned value.
*/
function scaleUpToWad(uint256 value, uint256 scale) internal pure returns (uint256) {
return scaleUp(value, scale, 18);
}
/**
* @notice Scales a value up from RAY. NOTE: The `scale` value must be
* less than 27.
* @param value to scale up.
* @param scale of the returned value.
*/
function scaleUpToRay(uint256 value, uint256 scale) internal pure returns (uint256) {
return scaleUp(value, scale, 27);
}
/**
* @notice Scales a value up from RAD. NOTE: The `scale` value must be
* less than 45.
* @param value to scale up.
* @param scale of the returned value.
*/
function scaleUpToRad(uint256 value, uint256 scale) internal pure returns (uint256) {
return scaleUp(value, scale, 45);
}
/**
* @notice Scales a value down to WAD. NOTE: The `scale` value must be
* greater than 18.
* @param value to scale down.
* @param scale of the returned value.
*/
function scaleDownToWad(uint256 value, uint256 scale) internal pure returns (uint256) {
return scaleDown(value, scale, 18);
}
/**
* @notice Scales a value down to RAY. NOTE: The `scale` value must be
* greater than 27.
* @param value to scale down.
* @param scale of the returned value.
*/
function scaleDownToRay(uint256 value, uint256 scale) internal pure returns (uint256) {
return scaleDown(value, scale, 27);
}
/**
* @notice Scales a value down to RAD. NOTE: The `scale` value must be
* greater than 45.
* @param value to scale down.
* @param scale of the returned value.
*/
function scaleDownToRad(uint256 value, uint256 scale) internal pure returns (uint256) {
return scaleDown(value, scale, 45);
}
/**
* @notice Scales a value up from one fixed-point precision to another.
* @param value to scale up.
* @param from Precision to scale from.
* @param to Precision to scale to.
*/
function scaleUp(uint256 value, uint256 from, uint256 to) internal pure returns (uint256) {
if (from >= to) revert NotScalingUp(from, to);
return value * (10 ** (to - from));
}
/**
* @notice Scales a value down from one fixed-point precision to another.
* @param value to scale down.
* @param from Precision to scale from.
* @param to Precision to scale to.
*/
function scaleDown(uint256 value, uint256 from, uint256 to) internal pure returns (uint256) {
if (from <= to) revert NotScalingDown(from, to);
return value / (10 ** (from - to));
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import { IReserveFeed } from "../../interfaces/IReserveFeed.sol";
import { WadRayMath, RAY } from "../../libraries/math/WadRayMath.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
// should equal to the number of feeds available in the contract
uint8 constant FEED_COUNT = 3;
uint256 constant UPDATE_COOLDOWN = 58 minutes;
/**
* @notice Reserve oracles are used to determine the LST provider exchange rate
* and is utilizated by Ion's liquidation module. Liquidations will only be
* triggered against this exchange rate and will be completely market-price
* agnostic. Importantly, this means that liquidations will only be triggered
* through lack of debt repayment or slashing events.
*
* @dev In order to protect against potential provider bugs or incorrect one-off
* values (malicious or accidental), the reserve oracle does not use live data.
* Instead it will query the exchange every intermittent period and persist the
* value and this value can only move up or down by a maximum percentage per query.
*
* If additional data sources are available, they can be involved as `FEED`s. If
* other `FEED`s are provided to the reserve oracle, a mean of all the `FEED`s
* is compared to the protocol exchange rate and the minimum of the two is used
* as the new exchange rate. This final value is subject to the bounding rules.
*
* @custom:security-contact [email protected]
*/
abstract contract ReserveOracle {
using WadRayMath for uint256;
uint8 public immutable ILK_INDEX;
uint8 public immutable QUORUM; // the number of feeds to aggregate
uint256 public immutable MAX_CHANGE; // maximum change allowed in percentage [ray] i.e. 3e25 [ray] would be 3%
IReserveFeed public immutable FEED0; // different reserve oracle feeds excluding the protocol exchange rate
IReserveFeed public immutable FEED1;
IReserveFeed public immutable FEED2;
uint256 public currentExchangeRate; // [wad] the bounded queried last time
uint256 public lastUpdated; // [wad] the bounded queried last time
// --- Events ---
event UpdateExchangeRate(uint256 exchangeRate);
// --- Errors ---
error InvalidQuorum(uint8 invalidQuorum);
error InvalidFeedLength(uint256 invalidLength);
error InvalidMaxChange(uint256 invalidMaxChange);
error InvalidMinMax(uint256 invalidMin, uint256 invalidMax);
error InvalidInitialization(uint256 invalidExchangeRate);
error UpdateCooldown(uint256 lastUpdated);
/**
* @notice Creates a new `ReserveOracle` instance.
* @param _ilkIndex of the associated collateral.
* @param _feeds Alternative data sources to be used for the reserve oracle.
* @param _quorum The number of feeds to aggregate.
* @param _maxChange Maximum percent change between exchange rate updates. [RAY]
*/
constructor(uint8 _ilkIndex, address[] memory _feeds, uint8 _quorum, uint256 _maxChange) {
if (_feeds.length != FEED_COUNT) revert InvalidFeedLength(_feeds.length);
if (_quorum > FEED_COUNT) revert InvalidQuorum(_quorum);
if (_maxChange == 0 || _maxChange > RAY) revert InvalidMaxChange(_maxChange);
ILK_INDEX = _ilkIndex;
QUORUM = _quorum;
MAX_CHANGE = _maxChange;
FEED0 = IReserveFeed(_feeds[0]);
FEED1 = IReserveFeed(_feeds[1]);
FEED2 = IReserveFeed(_feeds[2]);
}
// --- Override ---
/**
* @notice Returns the protocol exchange rate.
* @dev Must be implemented in the child contract with LST-specific logic.
* @return The protocol exchange rate.
*/
function _getProtocolExchangeRate() internal view virtual returns (uint256);
/**
* @notice Returns the protocol exchange rate.
* @return The protocol exchange rate.
*/
function getProtocolExchangeRate() external view returns (uint256) {
return _getProtocolExchangeRate();
}
/**
* @notice Queries values from whitelisted data feeds and calculates the
* mean. This does not include the protocol exchange rate.
* @param _ILK_INDEX of the associated collateral.
*/
function _aggregate(uint8 _ILK_INDEX) internal view returns (uint256 val) {
if (QUORUM == 0) {
return type(uint256).max;
} else if (QUORUM == 1) {
val = FEED0.getExchangeRate(_ILK_INDEX);
} else if (QUORUM == 2) {
uint256 feed0ExchangeRate = FEED0.getExchangeRate(_ILK_INDEX);
uint256 feed1ExchangeRate = FEED1.getExchangeRate(_ILK_INDEX);
val = ((feed0ExchangeRate + feed1ExchangeRate) / uint256(QUORUM));
} else if (QUORUM == 3) {
uint256 feed0ExchangeRate = FEED0.getExchangeRate(_ILK_INDEX);
uint256 feed1ExchangeRate = FEED1.getExchangeRate(_ILK_INDEX);
uint256 feed2ExchangeRate = FEED2.getExchangeRate(_ILK_INDEX);
val = ((feed0ExchangeRate + feed1ExchangeRate + feed2ExchangeRate) / uint256(QUORUM));
}
}
/**
* @notice Bounds the value between the min and the max.
* @param value The value to be bounded.
* @param min The minimum bound.
* @param max The maximum bound.
*/
function _bound(uint256 value, uint256 min, uint256 max) internal pure returns (uint256) {
if (min > max) revert InvalidMinMax(min, max);
return Math.max(min, Math.min(max, value));
}
/**
* @notice Initializes the `currentExchangeRate` state variable.
* @dev Called once during construction.
*/
function _initializeExchangeRate() internal {
currentExchangeRate = Math.min(_getProtocolExchangeRate(), _aggregate(ILK_INDEX));
if (currentExchangeRate == 0) {
revert InvalidInitialization(currentExchangeRate);
}
emit UpdateExchangeRate(currentExchangeRate);
}
/**
* @notice Updates the `currentExchangeRate` state variable.
* @dev Takes the minimum between the aggregated values and the protocol exchange rate,
* then bounds it up to the maximum change and writes the bounded value to the state.
* NOTE: keepers should call this update to reflect recent values
*/
function updateExchangeRate() external {
if (block.timestamp - lastUpdated < UPDATE_COOLDOWN) revert UpdateCooldown(lastUpdated);
uint256 _currentExchangeRate = currentExchangeRate;
uint256 minimum = Math.min(_getProtocolExchangeRate(), _aggregate(ILK_INDEX));
uint256 diff = _currentExchangeRate.rayMulDown(MAX_CHANGE);
uint256 bounded = _bound(minimum, _currentExchangeRate - diff, _currentExchangeRate + diff);
currentExchangeRate = bounded;
lastUpdated = block.timestamp;
emit UpdateExchangeRate(bounded);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.21;
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/**
* @notice An external Whitelist module that Ion's system-wide contracts can use
* to verify that a user is permitted to borrow or lend.
*
* A merkle whitelist is used to allow for a large number of addresses to be
* whitelisted without consuming infordinate amounts of gas for the updates.
*
* There is also a protocol whitelist that can be used to allow for a protocol
* controlled address to bypass the merkle proof check. These
* protocol-controlled contract are expected to perform whitelist checks
* themsleves on their own entrypoints.
*
* @dev The full merkle tree is stored off-chain and only the root is stored
* on-chain.
*
* @custom:security-contact [email protected]
*/
contract Whitelist is Ownable2Step {
mapping(address protocolControlledAddress => bool) public protocolWhitelist; // peripheral addresses that can bypass
// the merkle proof check
mapping(uint8 ilkIndex => bytes32) public borrowersRoot; // root of the merkle tree of borrowers for each ilk
bytes32 public lendersRoot; // root of the merkle tree of lenders for each ilk
// --- Errors ---
error NotWhitelistedBorrower(uint8 ilkIndex, address addr);
error NotWhitelistedLender(address addr);
/**
* @notice Creates a new `Whitelist` instance.
* @param _borrowersRoots List borrower merkle roots for each ilk.
* @param _lendersRoot The lender merkle root.
*/
constructor(bytes32[] memory _borrowersRoots, bytes32 _lendersRoot) Ownable(msg.sender) {
for (uint8 i = 0; i < _borrowersRoots.length; i++) {
borrowersRoot[i] = _borrowersRoots[i];
}
lendersRoot = _lendersRoot;
}
/**
* @notice Updates the borrower merkle root for a specific ilk.
* @param ilkIndex of the ilk.
* @param _borrowersRoot The new borrower merkle root.
*/
function updateBorrowersRoot(uint8 ilkIndex, bytes32 _borrowersRoot) external onlyOwner {
borrowersRoot[ilkIndex] = _borrowersRoot;
}
/**
* @notice Updates the lender merkle root.
* @param _lendersRoot The new lender merkle root.
*/
function updateLendersRoot(bytes32 _lendersRoot) external onlyOwner {
lendersRoot = _lendersRoot;
}
/**
* @notice Approves a protocol controlled address to bypass the merkle proof check.
* @param addr The address to approve.
*/
function approveProtocolWhitelist(address addr) external onlyOwner {
protocolWhitelist[addr] = true;
}
/**
* @notice Revokes a protocol controlled address to bypass the merkle proof check.
* @param addr The address to revoke approval for.
*/
function revokeProtocolWhitelist(address addr) external onlyOwner {
protocolWhitelist[addr] = false;
}
/**
* @notice Called by external modifiers to prove inclusion as a borrower.
* @dev If the root is just zero, then the whitelist is effectively turned
* off as every address will be allowed.
* @return True if the addr is part of the borrower whitelist or the
* protocol whitelist. False otherwise.
*/
function isWhitelistedBorrower(
uint8 ilkIndex,
address poolCaller,
address addr,
bytes32[] calldata proof
)
external
view
returns (bool)
{
if (protocolWhitelist[poolCaller]) return true;
bytes32 root = borrowersRoot[ilkIndex];
if (root == 0) return true;
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(addr))));
if (MerkleProof.verify(proof, root, leaf)) {
return true;
} else {
revert NotWhitelistedBorrower(ilkIndex, addr);
}
}
/**
* @notice Called by external modifiers to prove inclusion as a lender.
* @dev If the root is just zero, then the whitelist is effectively turned
* off as every address will be allowed.
* @return True if the addr is part of the lender whitelist or the protocol
* whitelist. False otherwise.
*/
function isWhitelistedLender(
address poolCaller,
address addr,
bytes32[] calldata proof
)
external
view
returns (bool)
{
if (protocolWhitelist[poolCaller]) return true;
bytes32 root = lendersRoot;
if (root == bytes32(0)) return true;
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(addr))));
if (MerkleProof.verify(proof, root, leaf)) {
return true;
} else {
revert NotWhitelistedLender(addr);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import { ReserveOracle } from "../../oracles/reserve/ReserveOracle.sol";
import { WadRayMath, RAY } from "../../libraries/math/WadRayMath.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
/**
* @notice The `SpotOracle` is supposed to reflect the current market price of a
* collateral asset. It is used by `IonPool` to determine the health factor of a
* vault as a user is opening or closing a position.
*
* NOTE: The price data provided by this contract is not used by the liquidation
* module at all.
*
* The spot price will also always be bounded by the collateral's corresponding
* reserve oracle price to ensure that a user can never open position that is
* directly liquidatable.
*
* @custom:security-contact [email protected]
*/
abstract contract SpotOracle {
using WadRayMath for uint256;
uint256 public immutable LTV; // max LTV for a position (below liquidation threshold) [ray]
ReserveOracle public immutable RESERVE_ORACLE;
// --- Errors ---
error InvalidLtv(uint256 ltv);
error InvalidReserveOracle();
/**
* @notice Creates a new `SpotOracle` instance.
* @param _ltv Loan to value ratio for the collateral.
* @param _reserveOracle Address for the associated reserve oracle.
*/
constructor(uint256 _ltv, address _reserveOracle) {
if (_ltv > RAY) {
revert InvalidLtv(_ltv);
}
if (address(_reserveOracle) == address(0)) {
revert InvalidReserveOracle();
}
LTV = _ltv;
RESERVE_ORACLE = ReserveOracle(_reserveOracle);
}
/**
* @notice Gets the price of the collateral asset in ETH.
* @dev Overridden by collateral specific spot oracle contracts.
* @return price of the asset in ETH. [WAD]
*/
function getPrice() public view virtual returns (uint256 price);
// @dev Gets the market price multiplied by the LTV.
// @return spot value of the asset in ETH [ray]
/**
* @notice Gets the risk-adjusted market price.
* @return spot The risk-adjusted market price.
*/
function getSpot() external view returns (uint256 spot) {
uint256 price = getPrice(); // must be [wad]
uint256 exchangeRate = RESERVE_ORACLE.currentExchangeRate();
// Min the price with reserve oracle before multiplying by ltv
uint256 min = Math.min(price, exchangeRate); // [wad]
spot = LTV.wadMulDown(min); // [ray] * [wad] / [wad] = [ray]
}
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.21;
import { WadRayMath, RAY } from "../libraries/math/WadRayMath.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC20Errors } from "./IERC20Errors.sol";
import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import { AccessControlDefaultAdminRulesUpgradeable } from
"@openzeppelin/contracts-upgradeable/access/extensions/AccessControlDefaultAdminRulesUpgradeable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MessageHashUtils } from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @title RewardToken
* @notice The supply-side reward accounting portion of the protocol. A lender's
* balance is measured in two parts: a static balance and a dynamic "supply
* factor". Their true balance is the product of the two values. The dynamic
* portion is then able to be used to distribute interest accrued to the lender.
*
* @custom:security-contact [email protected]
*/
abstract contract RewardToken is
ContextUpgradeable,
AccessControlDefaultAdminRulesUpgradeable,
IERC20Errors,
IERC20Metadata
{
using WadRayMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Cannot burn amount whose normalized value is less than zero.
*/
error InvalidBurnAmount();
/**
* @dev Cannot mint amount whose normalized value is less than zero.
*/
error InvalidMintAmount();
error InvalidUnderlyingAddress();
error InvalidTreasuryAddress();
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error InvalidReceiver(address receiver);
/**
* @dev Cannot transfer the token to address `self`
*/
error SelfTransfer(address self);
/**
* @dev Signature cannot be submitted after `deadline` has passed. Designed to
* mitigate replay attacks.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev `signer` does not match the `owner` of the tokens. `owner` did not approve.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param account Address whose token balance is insufficient.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error InsufficientBalance(address account, uint256 balance, uint256 needed);
event MintToTreasury(address indexed treasury, uint256 amount, uint256 supplyFactor);
event TreasuryUpdate(address treasury);
/// @custom:storage-location erc7201:ion.storage.RewardToken
struct RewardTokenStorage {
IERC20 underlying;
uint8 decimals;
// A user's true balance at any point will be the value in this mapping times the supplyFactor
string name;
string symbol;
address treasury;
uint256 normalizedTotalSupply; // [WAD]
uint256 supplyFactor; // [RAY]
mapping(address account => uint256) _normalizedBalances; // [WAD]
mapping(address account => mapping(address spender => uint256)) _allowances;
mapping(address account => uint256) nonces;
}
bytes32 public constant ION = keccak256("ION");
// keccak256(abi.encode(uint256(keccak256("ion.storage.RewardModule")) - 1)) & ~bytes32(uint256(0xff))
// solhint-disable-next-line
bytes32 private constant RewardTokenStorageLocation =
0xdb3a0d63a7808d7d0422c40bb62354f42bff7602a547c329c1453dbcbeef4900;
bytes private constant EIP712_REVISION = bytes("1");
bytes32 private constant EIP712_DOMAIN =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
function _getRewardTokenStorage() private pure returns (RewardTokenStorage storage $) {
assembly {
$.slot := RewardTokenStorageLocation
}
}
function _initialize(
address _underlying,
address _treasury,
uint8 decimals_,
string memory name_,
string memory symbol_
)
internal
onlyInitializing
{
if (_underlying == address(0)) revert InvalidUnderlyingAddress();
if (_treasury == address(0)) revert InvalidTreasuryAddress();
RewardTokenStorage storage $ = _getRewardTokenStorage();
$.underlying = IERC20(_underlying);
$.treasury = _treasury;
$.decimals = decimals_;
$.name = name_;
$.symbol = symbol_;
$.supplyFactor = RAY;
emit TreasuryUpdate(_treasury);
}
/**
*
* @param user to burn tokens from
* @param receiverOfUnderlying to send underlying tokens to
* @param amount to burn
*/
function _burn(address user, address receiverOfUnderlying, uint256 amount) internal returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
uint256 _supplyFactor = $.supplyFactor;
uint256 amountScaled = amount.rayDivUp(_supplyFactor);
if (amountScaled == 0) revert InvalidBurnAmount();
_burnNormalized(user, amountScaled);
$.underlying.safeTransfer(receiverOfUnderlying, amount);
emit Transfer(user, address(0), amount);
return _supplyFactor;
}
/**
*
* @param account to decrease balance of
* @param amount of normalized tokens to burn
*/
function _burnNormalized(address account, uint256 amount) private {
RewardTokenStorage storage $ = _getRewardTokenStorage();
if (account == address(0)) revert InvalidSender(address(0));
uint256 oldAccountBalance = $._normalizedBalances[account];
if (oldAccountBalance < amount) revert InsufficientBalance(account, oldAccountBalance, amount);
// Underflow impossible
unchecked {
$._normalizedBalances[account] = oldAccountBalance - amount;
}
$.normalizedTotalSupply -= amount;
}
/**
*
* @param user to mint tokens to
* @param senderOfUnderlying address to transfer underlying tokens from
* @param amount of reward tokens to mint
*/
function _mint(address user, address senderOfUnderlying, uint256 amount) internal returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
uint256 _supplyFactor = $.supplyFactor;
uint256 amountScaled = amount.rayDivDown(_supplyFactor); // [WAD] * [RAY] / [RAY] = [WAD]
if (amountScaled == 0) revert InvalidMintAmount();
_mintNormalized(user, amountScaled);
$.underlying.safeTransferFrom(senderOfUnderlying, address(this), amount);
emit Transfer(address(0), user, amount);
return _supplyFactor;
}
/**
*
* @param account to increase balance of
* @param amount of normalized tokens to mint
*/
function _mintNormalized(address account, uint256 amount) private {
if (account == address(0)) revert InvalidReceiver(address(0));
RewardTokenStorage storage $ = _getRewardTokenStorage();
$.normalizedTotalSupply += amount;
$._normalizedBalances[account] += amount;
}
/**
* @dev This function does not perform any rounding checks.
* @param amount of tokens to mint to treasury
*/
function _mintToTreasury(uint256 amount) internal {
if (amount == 0) return;
RewardTokenStorage storage $ = _getRewardTokenStorage();
uint256 _supplyFactor = $.supplyFactor;
address _treasury = $.treasury;
// Compared to the normal mint, we don't check for rounding errors. The
// amount to mint can easily be very small since it is a fraction of the
// interest accrued. In that case, the treasury will experience a (very
// small) loss, but it won't cause potentially valid transactions to
// fail.
_mintNormalized(_treasury, amount.rayDivDown(_supplyFactor));
emit Transfer(address(0), _treasury, amount);
emit MintToTreasury(_treasury, amount, _supplyFactor);
}
/**
*
* @param spender to approve
* @param amount to approve
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
*
* @param owner of tokens
* @param spender of tokens
* @param amount to approve
*/
function _approve(address owner, address spender, uint256 amount) internal {
if (owner == address(0)) revert ERC20InvalidApprover(address(0));
if (spender == address(0)) revert ERC20InvalidSpender(address(0));
RewardTokenStorage storage $ = _getRewardTokenStorage();
$._allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spends allowance
*/
function _spendAllowance(address owner, address spender, uint256 amount) private {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < amount) {
revert ERC20InsufficientAllowance(spender, currentAllowance, amount);
}
uint256 newAllowance;
// Underflow impossible
unchecked {
newAllowance = currentAllowance - amount;
}
RewardTokenStorage storage $ = _getRewardTokenStorage();
$._allowances[owner][spender] = newAllowance;
}
/**
* @dev Can only be called by owner of the tokens
* @param to transfer to
* @param amount to transfer
*/
function transfer(address to, uint256 amount) public returns (bool) {
_transfer(_msgSender(), to, amount);
emit Transfer(_msgSender(), to, amount);
return true;
}
/**
* @dev For use with `approve()`
* @param from to transfer from
* @param to to transfer to
* @param amount to transfer
*/
function transferFrom(address from, address to, uint256 amount) public returns (bool) {
_spendAllowance(from, _msgSender(), amount);
_transfer(from, to, amount);
emit Transfer(from, to, amount);
return true;
}
function _transfer(address from, address to, uint256 amount) private {
if (from == address(0)) revert ERC20InvalidSender(address(0));
if (to == address(0)) revert ERC20InvalidReceiver(address(0));
if (from == to) revert SelfTransfer(from);
RewardTokenStorage storage $ = _getRewardTokenStorage();
uint256 _supplyFactor = $.supplyFactor;
uint256 amountNormalized = amount.rayDivDown(_supplyFactor);
uint256 oldSenderBalance = $._normalizedBalances[from];
if (oldSenderBalance < amountNormalized) {
revert ERC20InsufficientBalance(from, oldSenderBalance, amountNormalized);
}
// Underflow impossible
unchecked {
$._normalizedBalances[from] = oldSenderBalance - amountNormalized;
}
$._normalizedBalances[to] += amountNormalized;
}
/**
* @dev implements the permit function as for
* https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
* @param owner The owner of the funds
* @param spender The spender
* @param value The amount
* @param deadline The deadline timestamp, type(uint256).max for max deadline
* @param v Signature param
* @param s Signature param
* @param r Signature param
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
public
virtual
{
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 domainSeparator = keccak256(
abi.encode(
EIP712_DOMAIN, keccak256(bytes(name())), keccak256(EIP712_REVISION), block.chainid, address(this)
)
);
bytes32 hash = MessageHashUtils.toTypedDataHash(domainSeparator, structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @dev Returns current allowance
* @param owner of tokens
* @param spender of tokens
*/
function allowance(address owner, address spender) public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $._allowances[owner][spender];
}
function nonces(address owner) public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $.nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
RewardTokenStorage storage $ = _getRewardTokenStorage();
unchecked {
// It is important to do x++ and not ++x here.
return $.nonces[owner]++;
}
}
function _setSupplyFactor(uint256 newSupplyFactor) internal {
RewardTokenStorage storage $ = _getRewardTokenStorage();
$.supplyFactor = newSupplyFactor;
}
/**
* @dev Updates the treasury address
* @param newTreasury address of new treasury
*/
function updateTreasury(address newTreasury) external onlyRole(ION) {
if (newTreasury == address(0)) revert InvalidTreasuryAddress();
RewardTokenStorage storage $ = _getRewardTokenStorage();
$.treasury = newTreasury;
emit TreasuryUpdate(newTreasury);
}
// --- Getters ---
/**
* @dev Address of underlying asset
*/
function underlying() public view returns (IERC20) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $.underlying;
}
/**
* @dev Decimals of the position asset
*/
function decimals() public view returns (uint8) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $.decimals;
}
/**
* @dev Current claim of the underlying token inclusive of interest to be accrued.
* @param user to get balance of
*/
function balanceOf(address user) public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
(uint256 totalSupplyFactorIncrease,,,,) = calculateRewardAndDebtDistribution();
return $._normalizedBalances[user].rayMulDown($.supplyFactor + totalSupplyFactorIncrease);
}
/**
* @dev Current claim of the underlying token without accounting for interest to be accrued.
*/
function balanceOfUnaccrued(address user) public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $._normalizedBalances[user].rayMulDown($.supplyFactor);
}
/**
* @dev Accounting is done in normalized balances
* @param user to get normalized balance of
*/
function normalizedBalanceOf(address user) external view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $._normalizedBalances[user];
}
/**
* @dev Name of the position asset
*/
function name() public view returns (string memory) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $.name;
}
/**
* @dev Symbol of the position asset
*/
function symbol() public view returns (string memory) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $.symbol;
}
/**
* @dev Current treasury address
*/
function treasury() public view returns (address) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $.treasury;
}
/**
* @dev Total claim of the underlying asset belonging to lenders not inclusive of the new interest to be accrued.
*/
function totalSupplyUnaccrued() public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
uint256 _normalizedTotalSupply = $.normalizedTotalSupply;
if (_normalizedTotalSupply == 0) {
return 0;
}
return _normalizedTotalSupply.rayMulDown($.supplyFactor);
}
/**
* @dev Total claim of the underlying asset belonging to lender inclusive of the new interest to be accrued.
*/
function totalSupply() public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
uint256 _normalizedTotalSupply = $.normalizedTotalSupply;
if (_normalizedTotalSupply == 0) {
return 0;
}
(uint256 totalSupplyFactorIncrease, uint256 totalTreasuryMintAmount,,,) = calculateRewardAndDebtDistribution();
return _normalizedTotalSupply.rayMulDown($.supplyFactor + totalSupplyFactorIncrease) + totalTreasuryMintAmount;
}
function normalizedTotalSupplyUnaccrued() public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $.normalizedTotalSupply;
}
/**
* @dev Normalized total supply.
*/
function normalizedTotalSupply() public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
(uint256 totalSupplyFactorIncrease, uint256 totalTreasuryMintAmount,,,) = calculateRewardAndDebtDistribution();
uint256 normalizedTreasuryMintAmount =
totalTreasuryMintAmount.rayDivDown($.supplyFactor + totalSupplyFactorIncrease);
return $.normalizedTotalSupply + normalizedTreasuryMintAmount;
}
function supplyFactorUnaccrued() public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
return $.supplyFactor;
}
/**
* @dev Current supply factor
*/
function supplyFactor() public view returns (uint256) {
RewardTokenStorage storage $ = _getRewardTokenStorage();
(uint256 totalSupplyFactorIncrease,,,,) = calculateRewardAndDebtDistribution();
return $.supplyFactor + totalSupplyFactorIncrease;
}
function calculateRewardAndDebtDistribution()
public
view
virtual
returns (
uint256 totalSupplyFactorIncrease,
uint256 totalTreasuryMintAmount,
uint104[] memory rateIncreases,
uint256 totalDebtIncrease,
uint48[] memory timestampIncreases
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;
import { IYieldOracle } from "./interfaces/IYieldOracle.sol";
import { WadRayMath } from "./libraries/math/WadRayMath.sol";
// forgefmt: disable-start
struct IlkData {
// Word 1
uint96 adjustedProfitMargin; // 27 decimals
uint96 minimumKinkRate; // 27 decimals
// Word 2
uint16 reserveFactor; // 4 decimals
uint96 adjustedBaseRate; // 27 decimals
uint96 minimumBaseRate; // 27 decimals
uint16 optimalUtilizationRate; // 4 decimals
uint16 distributionFactor; // 4 decimals
// Word 3
uint96 adjustedAboveKinkSlope; // 27 decimals
uint96 minimumAboveKinkSlope; // 27 decimals
}
// Word 1
//
// 256 240 216 192 96 0
// | | | | min_kink_rate | adj_profit_margin |
//
uint256 constant ADJUSTED_PROFIT_MARGIN_MASK = 0x0000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF;
uint256 constant MINIMUM_KINK_RATE_MASK = 0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000;
// Word 2
//
// 256 240 224 208 112 16 0
// | __ | | | min_base_rate | adj_base_rate | |
// ^ ^ ^
// ^ opt_util reserve_factor
// distribution_factor
uint256 constant RESERVE_FACTOR_MASK = 0x000000000000000000000000000000000000000000000000000000000000FFFF;
uint256 constant ADJUSTED_BASE_RATE_MASK = 0x000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF0000;
uint256 constant MINIMUM_BASE_RATE_MASK = 0x000000000000FFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000;
uint256 constant OPTIMAL_UTILIZATION_MASK = 0x00000000FFFF0000000000000000000000000000000000000000000000000000;
uint256 constant DISTRIBUTION_FACTOR_MASK = 0x0000FFFF00000000000000000000000000000000000000000000000000000000;
// Word 3
// 256 240 216 192 96 0
// | | | | min_above_kink_slope | adj_above_kink_slope |
//
uint256 constant ADJUSTED_ABOVE_KINK_SLOPE_MASK = 0x0000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF;
uint256 constant MINIMUM_ABOVE_KINK_SLOPE_MASK = 0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000;
// forgefmt: disable-end
// Word 1
uint8 constant ADJUSTED_PROFIT_MARGIN_SHIFT = 0;
uint8 constant MINIMUM_KINK_RATE_SHIFT = 96;
// Word 2
uint8 constant RESERVE_FACTOR_SHIFT = 0;
uint8 constant ADJUSTED_BASE_RATE_SHIFT = 16;
uint8 constant MINIMUM_BASE_RATE_SHIFT = 16 + 96;
uint8 constant OPTIMAL_UTILIZATION_SHIFT = 16 + 96 + 96;
uint8 constant DISTRIBUTION_FACTOR_SHIFT = 16 + 96 + 96 + 16;
// Word 3
uint8 constant ADJUSTED_ABOVE_KINK_SLOPE_SHIFT = 0;
uint8 constant MINIMUM_ABOVE_KINK_SLOPE_SHIFT = 96;
uint48 constant SECONDS_IN_A_YEAR = 31_536_000;
/**
* @notice An external contract that provides the APY for each collateral type.
* A modular design here allows for updating of the parameters at a later date
* without upgrading the core protocol.
*
* @dev Each collateral has its own interest rate model, and every operation on
* the `IonPool` (lend, withdraw, borrow, repay) will alter the interest rate
* for all collaterals. Therefore, before every operation, the previous interest
* rate must be accrued. Ion determines the interest rate for each collateral
* based on various collateral-specific parameters which must be stored
* on-chain. However, to iterate through all these parameters as contract
* storage on every operation introduces an immense gas overhead, especially as
* more collaterals are listed on Ion. Therefore, this contract is heavily
* optimized to reduce storage reads at the unfortunate cost of code-complexity.
*
* @custom:security-contact [email protected]
*/
contract InterestRate {
using WadRayMath for *;
error CollateralIndexOutOfBounds();
error DistributionFactorsDoNotSumToOne(uint256 sum);
error TotalDebtsLength(uint256 COLLATERAL_COUNT, uint256 totalIlkDebtsLength);
error InvalidMinimumKinkRate(uint256 minimumKinkRate, uint256 minimumBaseRate);
error InvalidIlkDataListLength(uint256 length);
error InvalidOptimalUtilizationRate(uint256 optimalUtilizationRate);
error InvalidReserveFactor(uint256 reserveFactor);
error InvalidYieldOracleAddress();
uint256 private constant MAX_ILKS = 8;
/**
* @dev Packed collateral configs
*/
uint256 private immutable ILKCONFIG_0A;
uint256 private immutable ILKCONFIG_0B;
uint256 private immutable ILKCONFIG_0C;
uint256 private immutable ILKCONFIG_1A;
uint256 private immutable ILKCONFIG_1B;
uint256 private immutable ILKCONFIG_1C;
uint256 private immutable ILKCONFIG_2A;
uint256 private immutable ILKCONFIG_2B;
uint256 private immutable ILKCONFIG_2C;
uint256 private immutable ILKCONFIG_3A;
uint256 private immutable ILKCONFIG_3B;
uint256 private immutable ILKCONFIG_3C;
uint256 private immutable ILKCONFIG_4A;
uint256 private immutable ILKCONFIG_4B;
uint256 private immutable ILKCONFIG_4C;
uint256 private immutable ILKCONFIG_5A;
uint256 private immutable ILKCONFIG_5B;
uint256 private immutable ILKCONFIG_5C;
uint256 private immutable ILKCONFIG_6A;
uint256 private immutable ILKCONFIG_6B;
uint256 private immutable ILKCONFIG_6C;
uint256 private immutable ILKCONFIG_7A;
uint256 private immutable ILKCONFIG_7B;
uint256 private immutable ILKCONFIG_7C;
uint256 public immutable COLLATERAL_COUNT;
IYieldOracle public immutable YIELD_ORACLE;
/**
* @notice Creates a new `InterestRate` instance.
* @param ilkDataList List of ilk configs.
* @param _yieldOracle Address of the Yield oracle.
*/
constructor(IlkData[] memory ilkDataList, IYieldOracle _yieldOracle) {
if (address(_yieldOracle) == address(0)) revert InvalidYieldOracleAddress();
if (ilkDataList.length > MAX_ILKS) revert InvalidIlkDataListLength(ilkDataList.length);
COLLATERAL_COUNT = ilkDataList.length;
YIELD_ORACLE = _yieldOracle;
uint256 distributionFactorSum = 0;
for (uint256 i = 0; i < COLLATERAL_COUNT;) {
distributionFactorSum += ilkDataList[i].distributionFactor;
if (ilkDataList[i].minimumKinkRate < ilkDataList[i].minimumBaseRate) {
revert InvalidMinimumKinkRate(ilkDataList[i].minimumKinkRate, ilkDataList[i].minimumBaseRate);
}
if (ilkDataList[i].optimalUtilizationRate == 0) {
revert InvalidOptimalUtilizationRate(ilkDataList[i].optimalUtilizationRate);
}
if (ilkDataList[i].reserveFactor > 1e4) {
revert InvalidReserveFactor(ilkDataList[i].reserveFactor);
}
// forgefmt: disable-next-line
unchecked { ++i; }
}
if (distributionFactorSum != 1e4) revert DistributionFactorsDoNotSumToOne(distributionFactorSum);
(ILKCONFIG_0A, ILKCONFIG_0B, ILKCONFIG_0C) = _packCollateralConfig(ilkDataList, 0);
(ILKCONFIG_1A, ILKCONFIG_1B, ILKCONFIG_1C) = _packCollateralConfig(ilkDataList, 1);
(ILKCONFIG_2A, ILKCONFIG_2B, ILKCONFIG_2C) = _packCollateralConfig(ilkDataList, 2);
(ILKCONFIG_3A, ILKCONFIG_3B, ILKCONFIG_3C) = _packCollateralConfig(ilkDataList, 3);
(ILKCONFIG_4A, ILKCONFIG_4B, ILKCONFIG_4C) = _packCollateralConfig(ilkDataList, 4);
(ILKCONFIG_5A, ILKCONFIG_5B, ILKCONFIG_5C) = _packCollateralConfig(ilkDataList, 5);
(ILKCONFIG_6A, ILKCONFIG_6B, ILKCONFIG_6C) = _packCollateralConfig(ilkDataList, 6);
(ILKCONFIG_7A, ILKCONFIG_7B, ILKCONFIG_7C) = _packCollateralConfig(ilkDataList, 7);
}
/**
* @notice Helper function to pack the collateral configs into 3 words. This
* function is only called during construction.
* @param ilkDataList The list of ilk configs.
* @param index The ilkIndex to pack.
* @return packedConfig_a
* @return packedConfig_b
* @return packedConfig_c
*/
function _packCollateralConfig(
IlkData[] memory ilkDataList,
uint256 index
)
private
view
returns (uint256 packedConfig_a, uint256 packedConfig_b, uint256 packedConfig_c)
{
if (index >= COLLATERAL_COUNT) return (0, 0, 0);
IlkData memory ilkData = ilkDataList[index];
packedConfig_a = (
uint256(ilkData.adjustedProfitMargin) << ADJUSTED_PROFIT_MARGIN_SHIFT
| uint256(ilkData.minimumKinkRate) << MINIMUM_KINK_RATE_SHIFT
);
packedConfig_b = (
uint256(ilkData.reserveFactor) << RESERVE_FACTOR_SHIFT
| uint256(ilkData.adjustedBaseRate) << ADJUSTED_BASE_RATE_SHIFT
| uint256(ilkData.minimumBaseRate) << MINIMUM_BASE_RATE_SHIFT
| uint256(ilkData.optimalUtilizationRate) << OPTIMAL_UTILIZATION_SHIFT
| uint256(ilkData.distributionFactor) << DISTRIBUTION_FACTOR_SHIFT
);
packedConfig_c = (
uint256(ilkData.adjustedAboveKinkSlope) << ADJUSTED_ABOVE_KINK_SLOPE_SHIFT
| uint256(ilkData.minimumAboveKinkSlope) << MINIMUM_ABOVE_KINK_SLOPE_SHIFT
);
}
/**
* @notice Helper function to unpack the collateral configs from the 3
* words.
* @param index The ilkIndex to unpack.
* @return ilkData The unpacked collateral config.
*/
function unpackCollateralConfig(uint256 index) external view returns (IlkData memory ilkData) {
return _unpackCollateralConfig(index);
}
function _unpackCollateralConfig(uint256 index) internal view returns (IlkData memory ilkData) {
if (index > COLLATERAL_COUNT - 1) revert CollateralIndexOutOfBounds();
uint256 packedConfig_a;
uint256 packedConfig_b;
uint256 packedConfig_c;
if (index == 0) {
packedConfig_a = ILKCONFIG_0A;
packedConfig_b = ILKCONFIG_0B;
packedConfig_c = ILKCONFIG_0C;
} else if (index == 1) {
packedConfig_a = ILKCONFIG_1A;
packedConfig_b = ILKCONFIG_1B;
packedConfig_c = ILKCONFIG_1C;
} else if (index == 2) {
packedConfig_a = ILKCONFIG_2A;
packedConfig_b = ILKCONFIG_2B;
packedConfig_c = ILKCONFIG_2C;
} else if (index == 3) {
packedConfig_a = ILKCONFIG_3A;
packedConfig_b = ILKCONFIG_3B;
packedConfig_c = ILKCONFIG_3C;
} else if (index == 4) {
packedConfig_a = ILKCONFIG_4A;
packedConfig_b = ILKCONFIG_4B;
packedConfig_c = ILKCONFIG_4C;
} else if (index == 5) {
packedConfig_a = ILKCONFIG_5A;
packedConfig_b = ILKCONFIG_5B;
packedConfig_c = ILKCONFIG_5C;
} else if (index == 6) {
packedConfig_a = ILKCONFIG_6A;
packedConfig_b = ILKCONFIG_6B;
packedConfig_c = ILKCONFIG_6C;
} else if (index == 7) {
packedConfig_a = ILKCONFIG_7A;
packedConfig_b = ILKCONFIG_7B;
packedConfig_c = ILKCONFIG_7C;
}
uint96 adjustedProfitMargin =
uint96((packedConfig_a & ADJUSTED_PROFIT_MARGIN_MASK) >> ADJUSTED_PROFIT_MARGIN_SHIFT);
uint96 minimumKinkRate = uint96((packedConfig_a & MINIMUM_KINK_RATE_MASK) >> MINIMUM_KINK_RATE_SHIFT);
uint16 reserveFactor = uint16((packedConfig_b & RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_SHIFT);
uint96 adjustedBaseRate = uint96((packedConfig_b & ADJUSTED_BASE_RATE_MASK) >> ADJUSTED_BASE_RATE_SHIFT);
uint96 minimumBaseRate = uint96((packedConfig_b & MINIMUM_BASE_RATE_MASK) >> MINIMUM_BASE_RATE_SHIFT);
uint16 optimalUtilizationRate = uint16((packedConfig_b & OPTIMAL_UTILIZATION_MASK) >> OPTIMAL_UTILIZATION_SHIFT);
uint16 distributionFactor = uint16((packedConfig_b & DISTRIBUTION_FACTOR_MASK) >> DISTRIBUTION_FACTOR_SHIFT);
uint96 adjustedAboveKinkSlope =
uint96((packedConfig_c & ADJUSTED_ABOVE_KINK_SLOPE_MASK) >> ADJUSTED_ABOVE_KINK_SLOPE_SHIFT);
uint96 minimumAboveKinkSlope =
uint96((packedConfig_c & MINIMUM_ABOVE_KINK_SLOPE_MASK) >> MINIMUM_ABOVE_KINK_SLOPE_SHIFT);
ilkData = IlkData({
adjustedProfitMargin: adjustedProfitMargin,
minimumKinkRate: minimumKinkRate,
reserveFactor: reserveFactor,
adjustedBaseRate: adjustedBaseRate,
minimumBaseRate: minimumBaseRate,
optimalUtilizationRate: optimalUtilizationRate,
distributionFactor: distributionFactor,
adjustedAboveKinkSlope: adjustedAboveKinkSlope,
minimumAboveKinkSlope: minimumAboveKinkSlope
});
}
/**
* @notice Calculates the interest rate for a given collateral.
* @param ilkIndex Index of the collateral.
* @param totalIlkDebt Total debt of the collateral. [RAD]
* @param totalEthSupply Total eth supply of the system. [WAD]
* @return The borrow rate for the collateral. [RAY]
* @return The reserve factor for the collateral. [RAY]
*/
function calculateInterestRate(
uint256 ilkIndex,
uint256 totalIlkDebt,
uint256 totalEthSupply
)
external
view
returns (uint256, uint256)
{
IlkData memory ilkData = _unpackCollateralConfig(ilkIndex);
uint256 optimalUtilizationRateRay = ilkData.optimalUtilizationRate.scaleUpToRay(4);
uint256 collateralApyRayInSeconds = YIELD_ORACLE.apys(ilkIndex).scaleUpToRay(8) / SECONDS_IN_A_YEAR;
uint256 distributionFactor = ilkData.distributionFactor;
// The only time the distribution factor will be set to 0 is when a
// market has been sunset. In this case, we want to prevent division by
// 0, but we also want to prevent the borrow rate from skyrocketing. So
// we will return a reasonable borrow rate of kink utilization on the
// minimum curve.
if (distributionFactor == 0) {
return (ilkData.minimumKinkRate, ilkData.reserveFactor.scaleUpToRay(4));
}
// If the `totalEthSupply` is small enough to truncate to zero, then
// treat the utilization as zero.
uint256 totalEthSupplyScaled = totalEthSupply.wadMulDown(distributionFactor.scaleUpToWad(4));
// [RAD] / [WAD] = [RAY]
uint256 utilizationRate = totalEthSupplyScaled == 0 ? 0 : totalIlkDebt / totalEthSupplyScaled;
// Avoid stack too deep
uint256 adjustedBelowKinkSlope;
{
uint256 slopeNumerator;
unchecked {
slopeNumerator = collateralApyRayInSeconds - ilkData.adjustedProfitMargin - ilkData.adjustedBaseRate;
}
// Underflow occurred
// If underflow occurred, then the Apy was too low or the profitMargin was too high and
// we would want to switch to minimum borrow rate. Set slopeNumerator to zero such
// that adjusted borrow rate is below the minimum borrow rate.
if (slopeNumerator > collateralApyRayInSeconds) {
slopeNumerator = 0;
}
adjustedBelowKinkSlope = slopeNumerator.rayDivDown(optimalUtilizationRateRay);
}
uint256 minimumBelowKinkSlope =
(ilkData.minimumKinkRate - ilkData.minimumBaseRate).rayDivDown(optimalUtilizationRateRay);
// Below kink
if (utilizationRate < optimalUtilizationRateRay) {
uint256 adjustedBorrowRate = adjustedBelowKinkSlope.rayMulDown(utilizationRate) + ilkData.adjustedBaseRate;
uint256 minimumBorrowRate = minimumBelowKinkSlope.rayMulDown(utilizationRate) + ilkData.minimumBaseRate;
if (adjustedBorrowRate < minimumBorrowRate) {
return (minimumBorrowRate, ilkData.reserveFactor.scaleUpToRay(4));
} else {
return (adjustedBorrowRate, ilkData.reserveFactor.scaleUpToRay(4));
}
}
// Above kink
else {
// For the above kink calculation, we will use the below kink slope
// for all utilization up until the kink. From that point on we will
// use the above kink slope.
uint256 excessUtil = utilizationRate - optimalUtilizationRateRay;
uint256 adjustedNormalRate =
adjustedBelowKinkSlope.rayMulDown(optimalUtilizationRateRay) + ilkData.adjustedBaseRate;
uint256 minimumNormalRate =
minimumBelowKinkSlope.rayMulDown(optimalUtilizationRateRay) + ilkData.minimumBaseRate;
// [WAD] * [RAY] / [WAD] = [RAY]
uint256 adjustedBorrowRate = ilkData.adjustedAboveKinkSlope.rayMulDown(excessUtil) + adjustedNormalRate;
uint256 minimumBorrowRate = ilkData.minimumAboveKinkSlope.rayMulDown(excessUtil) + minimumNormalRate;
if (adjustedBorrowRate < minimumBorrowRate) {
return (minimumBorrowRate, ilkData.reserveFactor.scaleUpToRay(4));
} else {
return (adjustedBorrowRate, ilkData.reserveFactor.scaleUpToRay(4));
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.21;
/**
* @title IReserveFeed interface
* @notice Interface for the reserve feeds for Ion Protocol.
*
*/
interface IReserveFeed {
/**
* @dev updates the total reserve of the validator backed asset
* @param ilkIndex the ilk index of the asset
* @param reserve the total ETH reserve of the asset in wei
*/
function updateExchangeRate(uint8 ilkIndex, uint256 reserve) external;
/**
* @dev returns the total reserve of the validator backed asset
* @param ilkIndex the ilk index of the asset
* @return the total ETH reserve of the asset in wei
*/
function getExchangeRate(uint8 ilkIndex) external view returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @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.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.20;
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*/
library MerkleProof {
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proofLen != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proofLen != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Sorts the pair (a, b) and hashes the result.
*/
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.21;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlDefaultAdminRules.sol)
pragma solidity ^0.8.20;
import {IAccessControlDefaultAdminRules} from "@openzeppelin/contracts/access/extensions/IAccessControlDefaultAdminRules.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC5313} from "@openzeppelin/contracts/interfaces/IERC5313.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows specifying special rules to manage
* the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions
* over other roles that may potentially have privileged rights in the system.
*
* If a specific role doesn't have an admin role assigned, the holder of the
* `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it.
*
* This contract implements the following risk mitigations on top of {AccessControl}:
*
* * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced.
* * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account.
* * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted.
* * The delay can be changed by scheduling, see {changeDefaultAdminDelay}.
* * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`.
*
* Example usage:
*
* ```solidity
* contract MyToken is AccessControlDefaultAdminRules {
* constructor() AccessControlDefaultAdminRules(
* 3 days,
* msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder
* ) {}
* }
* ```
*/
abstract contract AccessControlDefaultAdminRulesUpgradeable is Initializable, IAccessControlDefaultAdminRules, IERC5313, AccessControlUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControlDefaultAdminRules
struct AccessControlDefaultAdminRulesStorage {
// pending admin pair read/written together frequently
address _pendingDefaultAdmin;
uint48 _pendingDefaultAdminSchedule; // 0 == unset
uint48 _currentDelay;
address _currentDefaultAdmin;
// pending delay pair read/written together frequently
uint48 _pendingDelay;
uint48 _pendingDelaySchedule; // 0 == unset
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlDefaultAdminRules")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlDefaultAdminRulesStorageLocation = 0xeef3dac4538c82c8ace4063ab0acd2d15cdb5883aa1dff7c2673abb3d8698400;
function _getAccessControlDefaultAdminRulesStorage() private pure returns (AccessControlDefaultAdminRulesStorage storage $) {
assembly {
$.slot := AccessControlDefaultAdminRulesStorageLocation
}
}
/**
* @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address.
*/
function __AccessControlDefaultAdminRules_init(uint48 initialDelay, address initialDefaultAdmin) internal onlyInitializing {
__AccessControlDefaultAdminRules_init_unchained(initialDelay, initialDefaultAdmin);
}
function __AccessControlDefaultAdminRules_init_unchained(uint48 initialDelay, address initialDefaultAdmin) internal onlyInitializing {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
if (initialDefaultAdmin == address(0)) {
revert AccessControlInvalidDefaultAdmin(address(0));
}
$._currentDelay = initialDelay;
_grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC5313-owner}.
*/
function owner() public view virtual returns (address) {
return defaultAdmin();
}
///
/// Override AccessControl role management
///
/**
* @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) {
if (role == DEFAULT_ADMIN_ROLE) {
revert AccessControlEnforcedDefaultAdminRules();
}
super.grantRole(role, account);
}
/**
* @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) {
if (role == DEFAULT_ADMIN_ROLE) {
revert AccessControlEnforcedDefaultAdminRules();
}
super.revokeRole(role, account);
}
/**
* @dev See {AccessControl-renounceRole}.
*
* For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling
* {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule
* has also passed when calling this function.
*
* After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions.
*
* NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin},
* thereby disabling any functionality that is only available for it, and the possibility of reassigning a
* non-administrated role.
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
(address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin();
if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
revert AccessControlEnforcedDefaultAdminDelay(schedule);
}
delete $._pendingDefaultAdminSchedule;
}
super.renounceRole(role, account);
}
/**
* @dev See {AccessControl-_grantRole}.
*
* For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the
* role has been previously renounced.
*
* NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE`
* assignable again. Make sure to guarantee this is the expected behavior in your implementation.
*/
function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
if (role == DEFAULT_ADMIN_ROLE) {
if (defaultAdmin() != address(0)) {
revert AccessControlEnforcedDefaultAdminRules();
}
$._currentDefaultAdmin = account;
}
return super._grantRole(role, account);
}
/**
* @dev See {AccessControl-_revokeRole}.
*/
function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
delete $._currentDefaultAdmin;
}
return super._revokeRole(role, account);
}
/**
* @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override {
if (role == DEFAULT_ADMIN_ROLE) {
revert AccessControlEnforcedDefaultAdminRules();
}
super._setRoleAdmin(role, adminRole);
}
///
/// AccessControlDefaultAdminRules accessors
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdmin() public view virtual returns (address) {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
return $._currentDefaultAdmin;
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
return ($._pendingDefaultAdmin, $._pendingDefaultAdminSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdminDelay() public view virtual returns (uint48) {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
uint48 schedule = $._pendingDelaySchedule;
return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? $._pendingDelay : $._currentDelay;
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
schedule = $._pendingDelaySchedule;
return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? ($._pendingDelay, schedule) : (0, 0);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) {
return 5 days;
}
///
/// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_beginDefaultAdminTransfer(newAdmin);
}
/**
* @dev See {beginDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _beginDefaultAdminTransfer(address newAdmin) internal virtual {
uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay();
_setPendingDefaultAdmin(newAdmin, newSchedule);
emit DefaultAdminTransferScheduled(newAdmin, newSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_cancelDefaultAdminTransfer();
}
/**
* @dev See {cancelDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _cancelDefaultAdminTransfer() internal virtual {
_setPendingDefaultAdmin(address(0), 0);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function acceptDefaultAdminTransfer() public virtual {
(address newDefaultAdmin, ) = pendingDefaultAdmin();
if (_msgSender() != newDefaultAdmin) {
// Enforce newDefaultAdmin explicit acceptance.
revert AccessControlInvalidDefaultAdmin(_msgSender());
}
_acceptDefaultAdminTransfer();
}
/**
* @dev See {acceptDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _acceptDefaultAdminTransfer() internal virtual {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
(address newAdmin, uint48 schedule) = pendingDefaultAdmin();
if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
revert AccessControlEnforcedDefaultAdminDelay(schedule);
}
_revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin());
_grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
delete $._pendingDefaultAdmin;
delete $._pendingDefaultAdminSchedule;
}
///
/// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_changeDefaultAdminDelay(newDelay);
}
/**
* @dev See {changeDefaultAdminDelay}.
*
* Internal function without access restriction.
*/
function _changeDefaultAdminDelay(uint48 newDelay) internal virtual {
uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay);
_setPendingDelay(newDelay, newSchedule);
emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_rollbackDefaultAdminDelay();
}
/**
* @dev See {rollbackDefaultAdminDelay}.
*
* Internal function without access restriction.
*/
function _rollbackDefaultAdminDelay() internal virtual {
_setPendingDelay(0, 0);
}
/**
* @dev Returns the amount of seconds to wait after the `newDelay` will
* become the new {defaultAdminDelay}.
*
* The value returned guarantees that if the delay is reduced, it will go into effect
* after a wait that honors the previously set delay.
*
* See {defaultAdminDelayIncreaseWait}.
*/
function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) {
uint48 currentDelay = defaultAdminDelay();
// When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up
// to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day
// to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new
// delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like
// using milliseconds instead of seconds.
//
// When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees
// that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled.
// For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days.
return
newDelay > currentDelay
? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48
: currentDelay - newDelay;
}
///
/// Private setters
///
/**
* @dev Setter of the tuple for pending admin and its schedule.
*
* May emit a DefaultAdminTransferCanceled event.
*/
function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
(, uint48 oldSchedule) = pendingDefaultAdmin();
$._pendingDefaultAdmin = newAdmin;
$._pendingDefaultAdminSchedule = newSchedule;
// An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted.
if (_isScheduleSet(oldSchedule)) {
// Emit for implicit cancellations when another default admin was scheduled.
emit DefaultAdminTransferCanceled();
}
}
/**
* @dev Setter of the tuple for pending delay and its schedule.
*
* May emit a DefaultAdminDelayChangeCanceled event.
*/
function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private {
AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
uint48 oldSchedule = $._pendingDelaySchedule;
if (_isScheduleSet(oldSchedule)) {
if (_hasSchedulePassed(oldSchedule)) {
// Materialize a virtual delay
$._currentDelay = $._pendingDelay;
} else {
// Emit for implicit cancellations when another delay was scheduled.
emit DefaultAdminDelayChangeCanceled();
}
}
$._pendingDelay = newDelay;
$._pendingDelaySchedule = newSchedule;
}
///
/// Private helpers
///
/**
* @dev Defines if an `schedule` is considered set. For consistency purposes.
*/
function _isScheduleSet(uint48 schedule) private pure returns (bool) {
return schedule != 0;
}
/**
* @dev Defines if an `schedule` is considered passed. For consistency purposes.
*/
function _hasSchedulePassed(uint48 schedule) private view returns (bool) {
return schedule < block.timestamp;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
interface IYieldOracle {
function apys(uint256 ilkIndex) external view returns (uint32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlDefaultAdminRules.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "../IAccessControl.sol";
/**
* @dev External interface of AccessControlDefaultAdminRules declared to support ERC165 detection.
*/
interface IAccessControlDefaultAdminRules is IAccessControl {
/**
* @dev The new default admin is not a valid default admin.
*/
error AccessControlInvalidDefaultAdmin(address defaultAdmin);
/**
* @dev At least one of the following rules was violated:
*
* - The `DEFAULT_ADMIN_ROLE` must only be managed by itself.
* - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time.
* - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps.
*/
error AccessControlEnforcedDefaultAdminRules();
/**
* @dev The delay for transferring the default admin delay is enforced and
* the operation must wait until `schedule`.
*
* NOTE: `schedule` can be 0 indicating there's no transfer scheduled.
*/
error AccessControlEnforcedDefaultAdminDelay(uint48 schedule);
/**
* @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
* address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule`
* passes.
*/
event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);
/**
* @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule.
*/
event DefaultAdminTransferCanceled();
/**
* @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
* delay to be applied between default admin transfer after `effectSchedule` has passed.
*/
event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);
/**
* @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
*/
event DefaultAdminDelayChangeCanceled();
/**
* @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
*/
function defaultAdmin() external view returns (address);
/**
* @dev Returns a tuple of a `newAdmin` and an accept schedule.
*
* After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
* by calling {acceptDefaultAdminTransfer}, completing the role transfer.
*
* A zero value only in `acceptSchedule` indicates no pending admin transfer.
*
* NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
*/
function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);
/**
* @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started.
*
* This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set
* the acceptance schedule.
*
* NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this
* function returns the new delay. See {changeDefaultAdminDelay}.
*/
function defaultAdminDelay() external view returns (uint48);
/**
* @dev Returns a tuple of `newDelay` and an effect schedule.
*
* After the `schedule` passes, the `newDelay` will get into effect immediately for every
* new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
*
* A zero value only in `effectSchedule` indicates no pending delay change.
*
* NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
* will be zero after the effect schedule.
*/
function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule);
/**
* @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance
* after the current timestamp plus a {defaultAdminDelay}.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* Emits a DefaultAdminRoleChangeStarted event.
*/
function beginDefaultAdminTransfer(address newAdmin) external;
/**
* @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
*
* A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* May emit a DefaultAdminTransferCanceled event.
*/
function cancelDefaultAdminTransfer() external;
/**
* @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
*
* After calling the function:
*
* - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
* - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
* - {pendingDefaultAdmin} should be reset to zero values.
*
* Requirements:
*
* - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
* - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
*/
function acceptDefaultAdminTransfer() external;
/**
* @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting
* into effect after the current timestamp plus a {defaultAdminDelay}.
*
* This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this
* method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay}
* set before calling.
*
* The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then
* calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin}
* complete transfer (including acceptance).
*
* The schedule is designed for two scenarios:
*
* - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by
* {defaultAdminDelayIncreaseWait}.
* - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`.
*
* A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event.
*/
function changeDefaultAdminDelay(uint48 newDelay) external;
/**
* @dev Cancels a scheduled {defaultAdminDelay} change.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* May emit a DefaultAdminDelayChangeCanceled event.
*/
function rollbackDefaultAdminDelay() external;
/**
* @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay})
* to take effect. Default to 5 days.
*
* When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with
* the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds)
* that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can
* be overrode for a custom {defaultAdminDelay} increase scheduling.
*
* IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
* there's a risk of setting a high new delay that goes into effect almost immediately without the
* possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds).
*/
function defaultAdminDelayIncreaseWait() external view returns (uint48);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5313.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface for the Light Contract Ownership Standard.
*
* A standardized minimal interface required to identify an account that controls a contract
*/
interface IERC5313 {
/**
* @dev Gets the address of the owner.
*/
function owner() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}{
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@balancer-labs/v2-interfaces/=lib/balancer-v2-monorepo/pkg/interfaces/",
"@balancer-labs/v2-pool-stable/=lib/balancer-v2-monorepo/pkg/pool-stable/",
"@chainlink/contracts/=lib/chainlink/contracts/",
"@uniswap/v3-periphery/=lib/v3-periphery/",
"@uniswap/v3-core/=lib/v3-core/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
"chainlink/=lib/chainlink/",
"ds-test/=lib/forge-safe/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-safe/=lib/forge-safe/src/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solady/=lib/solady/",
"solidity-stringutils/=lib/forge-safe/lib/surl/lib/solidity-stringutils/",
"solmate/=lib/forge-safe/lib/solmate/src/",
"surl/=lib/forge-safe/lib/surl/",
"v3-core/=lib/v3-core/",
"v3-periphery/=lib/v3-periphery/contracts/",
"solarray/=lib/solarray/src/",
"pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "shanghai",
"viaIR": false,
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_ionPool","type":"address"},{"internalType":"address","name":"_protocol","type":"address"},{"internalType":"address","name":"_reserveOracle","type":"address"},{"internalType":"uint256","name":"_liquidationThreshold","type":"uint256"},{"internalType":"uint256","name":"_targetHealth","type":"uint256"},{"internalType":"uint256","name":"_reserveFactor","type":"uint256"},{"internalType":"uint256","name":"_maxDiscount","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"ExchangeRateCannotBeZero","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"uint256","name":"liquidationThreshold","type":"uint256"}],"name":"InvalidLiquidationThreshold","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"InvalidLiquidationThresholdsLength","type":"error"},{"inputs":[{"internalType":"uint256","name":"maxDiscount","type":"uint256"}],"name":"InvalidMaxDiscount","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"InvalidMaxDiscountsLength","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"InvalidReserveOraclesLength","type":"error"},{"inputs":[{"internalType":"uint256","name":"targetHealth","type":"uint256"}],"name":"InvalidTargetHealth","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[{"internalType":"uint256","name":"from","type":"uint256"},{"internalType":"uint256","name":"to","type":"uint256"}],"name":"NotScalingUp","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintToInt","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"healthRatio","type":"uint256"}],"name":"VaultIsNotUnsafe","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"initiator","type":"address"},{"indexed":true,"internalType":"address","name":"kpr","type":"address"},{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"repay","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"gemOut","type":"uint256"}],"name":"Liquidate","type":"event"},{"inputs":[],"name":"BASE_DISCOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIQUIDATION_THRESHOLD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_DISCOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL","outputs":[{"internalType":"contract IonPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PROTOCOL","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"RESERVE_ORACLE","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TARGET_HEALTH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNDERLYING","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"vault","type":"address"}],"name":"getRepayAmt","outputs":[{"internalType":"uint256","name":"repay","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"kpr","type":"address"}],"name":"liquidate","outputs":[{"internalType":"uint256","name":"repayAmount","type":"uint256"},{"internalType":"uint256","name":"gemOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
61018060405234801562000011575f80fd5b5060405162001c0338038062001c038339810160408190526200003491620003c8565b6001600160a01b0380881661014052861661012052866b033b2e3c9fd0803ce800000082106200007f576040516370d4111760e11b8152600481018390526024015b60405180910390fd5b845f03620000a457604051636546229560e11b81526004810186905260240162000076565b620000c8620000c0836b033b2e3c9fd0803ce800000062000452565b86906200023a565b841015620000ed57604051630a10a28960e11b81526004810185905260240162000076565b6b033b2e3c9fd0803ce80000008410156200011f57604051630a10a28960e11b81526004810185905260240162000076565b608084905260a083905260c082905260408051636f307dc360e01b815290515f916001600160a01b03841691636f307dc3916004808201926020929091908290030181865afa15801562000175573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200019b919062000468565b60405163095ea7b360e01b81526001600160a01b0384811660048301525f1960248301529192509082169063095ea7b3906044016020604051808303815f875af1158015620001ec573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000212919062000486565b506001600160a01b039081166101605260e09590955250505050166101005250620005139050565b5f62000256836b033b2e3c9fd0803ce80000008460016200025f565b90505b92915050565b5f806200026e868686620002b9565b90506200027b836200037f565b80156200029a57505f8480620002955762000295620004a7565b868809115b15620002b057620002ad600182620004bb565b90505b95945050505050565b5f838302815f1985870982811083820303915050805f03620002f257838281620002e757620002e7620004a7565b049250505062000378565b808411620003135760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b5f6002826003811115620003975762000397620004d1565b620003a39190620004e5565b60ff166001149050919050565b6001600160a01b0381168114620003c5575f80fd5b50565b5f805f805f805f60e0888a031215620003df575f80fd5b8751620003ec81620003b0565b6020890151909750620003ff81620003b0565b60408901519096506200041281620003b0565b80955050606088015193506080880151925060a0880151915060c0880151905092959891949750929550565b634e487b7160e01b5f52601160045260245ffd5b818103818111156200025957620002596200043e565b5f6020828403121562000479575f80fd5b81516200037881620003b0565b5f6020828403121562000497575f80fd5b8151801515811462000378575f80fd5b634e487b7160e01b5f52601260045260245ffd5b808201808211156200025957620002596200043e565b634e487b7160e01b5f52602160045260245ffd5b5f60ff8316806200050457634e487b7160e01b5f52601260045260245ffd5b8060ff84160691505092915050565b60805160a05160c05160e05161010051610120516101405161016051611617620005ec5f395f81816101f4015261080101525f818161014501528181610316015281816103a70152818161055c015281816106860152818161082b015281816108f301528181610a5501528181610ae60152610c7301525f8181610193015261058501525f818160a40152610da701525f818161016c0152610dce01525f818161021b0152610df101525f8181610110015281816104b20152610bdf01525f81816101cd01528181610e7c0152610ed201526116175ff3fe608060405234801561000f575f80fd5b506004361061009b575f3560e01c806391b9b8271161006357806391b9b8271461018e578063a0d5f599146101b5578063ae539533146101c8578063c5d664c6146101ef578063e349556914610216575f80fd5b80631f5155c41461009f57806325840eda146100e357806349ed64341461010b5780637535d2461461014057806390a8ae9b14610167575b5f80fd5b6100c67f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b6100f66100f13660046112d5565b61023d565b604080519283526020830191909152016100da565b6101327f000000000000000000000000000000000000000000000000000000000000000081565b6040519081526020016100da565b6100c67f000000000000000000000000000000000000000000000000000000000000000081565b6101327f000000000000000000000000000000000000000000000000000000000000000081565b6100c67f000000000000000000000000000000000000000000000000000000000000000081565b6101326101c3366004611315565b6109d4565b6101327f000000000000000000000000000000000000000000000000000000000000000081565b6100c67f000000000000000000000000000000000000000000000000000000000000000081565b6101327f000000000000000000000000000000000000000000000000000000000000000081565b5f8061026c6040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b5f610275610d73565b90505f6102e7601283604001516001600160a01b031663a36849776040518163ffffffff1660e01b8152600401602060405180830381865afa1580156102bd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102e19190611346565b90610e18565b604051639a3db79b60e01b815260ff8a1660048201526001600160a01b0389811660248301529192505f9182917f000000000000000000000000000000000000000000000000000000000000000090911690639a3db79b906044016040805180830381865afa15801561035c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610380919061135d565b604051633c04b54760e01b815260ff8d16600482015291935091505f906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690633c04b54790602401602060405180830381865afa1580156103ec573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104109190611346565b9050835f036104325760405163150c57e560e01b815260040160405180910390fd5b84515f9061044a906104448787611393565b90610e2c565b90505f61046161045a8486611393565b8390610e43565b9050676765c793fa10079d601b1b811061049657604051630df91f7b60e11b8152600481018290526024015b60405180910390fd5b5f6104ac82676765c793fa10079d601b1b6113aa565b6104d6907f00000000000000000000000000000000000000000000000000000000000000006113bd565b905087602001518111156104ee5787602001516104f0565b805b905061051161050a82676765c793fa10079d601b1b6113aa565b8890610e5a565b60808a015261052d6105238587611393565b8951859084610e73565b89525061053c90508284611393565b8751111561066e5760408701839052602087018490526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001663979397438d8d7f0000000000000000000000000000000000000000000000000000000000000000806105ae8a6113d0565b8d604001516105bc906113d0565b6040518763ffffffff1660e01b81526004016105dd969594939291906113ea565b5f604051808303815f87803b1580156105f4575f80fd5b505af1158015610606573d5f803e3d5ffd5b5050506040808901516020808b015183519283529082015260ff8f1692506001600160a01b038d169133917f54f9b006b19a44694e56b0d6a57f34c420bf88da7373f9d0f3380e5f4b70951e910160405180910390a45f8098509850505050505050506109cc565b604051638ba7650760e01b815260ff8d1660048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690638ba7650790602401602060405180830381865afa1580156106d3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106f79190611346565b87516107038486611393565b61070d91906113aa565b10156107495761071d8284611393565b87526040870183905260808701516107358385611393565b61073f9190611438565b60208801526107ab565b8651610756908390611438565b604088015286515f9061076a90849061144b565b11156107825786604001805161077f9061145e565b90525b608087015187516107939190611438565b602088015260408701516107a8908390611393565b87525b86515f906107c590676765c793fa10079d601b1b90611438565b90505f676765c793fa10079d601b1b895f01516107e2919061144b565b11156107f4576107f18161145e565b90505b6108296001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016333084610f0d565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663979397438e8e8e306108698e60200151610f6d565b610872906113d0565b61087f8f60400151610f6d565b610888906113d0565b6040518763ffffffff1660e01b81526004016108a9969594939291906113ea565b5f604051808303815f87803b1580156108c0575f80fd5b505af11580156108d2573d5f803e3d5ffd5b50508951604051631b063dfb60e31b815230600482015260248101919091527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316925063d831efd891506044015f604051808303815f87803b15801561093e575f80fd5b505af1158015610950573d5f803e3d5ffd5b505050508c60ff168b6001600160a01b0316336001600160a01b03167f54f9b006b19a44694e56b0d6a57f34c420bf88da7373f9d0f3380e5f4b70951e8b604001518c602001516040516109ae929190918252602082015260400190565b60405180910390a4875f015188602001519950995050505050505050505b935093915050565b5f806109de610d73565b90505f610a26601283604001516001600160a01b031663a36849776040518163ffffffff1660e01b8152600401602060405180830381865afa1580156102bd573d5f803e3d5ffd5b604051639a3db79b60e01b815260ff871660048201526001600160a01b0386811660248301529192505f9182917f000000000000000000000000000000000000000000000000000000000000000090911690639a3db79b906044016040805180830381865afa158015610a9b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610abf919061135d565b604051633c04b54760e01b815260ff8a16600482015291935091505f906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690633c04b54790602401602060405180830381865afa158015610b2b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b4f9190611346565b9050835f03610b715760405163150c57e560e01b815260040160405180910390fd5b84515f90610b83906104448787611393565b90505f610b9361045a8486611393565b9050676765c793fa10079d601b1b8110610bc357604051630df91f7b60e11b81526004810182905260240161048d565b5f610bd982676765c793fa10079d601b1b6113aa565b610c03907f00000000000000000000000000000000000000000000000000000000000000006113bd565b90508760200151811115610c1b578760200151610c1d565b805b90505f610c37610c2d8688611393565b8a51869085610e73565b9050610c438587611393565b811115610c5b575f9950505050505050505050610d6d565b604051638ba7650760e01b815260ff8d1660048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690638ba7650790602401602060405180830381865afa158015610cc0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ce49190611346565b81610cef8789611393565b610cf991906113aa565b1015610d0c57610d098587611393565b90505b5f610d22676765c793fa10079d601b1b8361144b565b11610d4157610d3c676765c793fa10079d601b1b82611438565b610d61565b610d56676765c793fa10079d601b1b82611438565b610d619060016113bd565b99505050505050505050505b92915050565b610d9d60405180606001604052805f81526020015f81526020015f6001600160a01b031681525090565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001660408201527f000000000000000000000000000000000000000000000000000000000000000081527f0000000000000000000000000000000000000000000000000000000000000000602082015290565b5f610e258383601b610f9d565b9392505050565b5f610e258383676765c793fa10079d601b1b610fef565b5f610e2583676765c793fa10079d601b1b84610fef565b5f610e258383676765c793fa10079d601b1b60016110ae565b5f8084610ea0877f0000000000000000000000000000000000000000000000000000000000000000610e5a565b610eaa91906113aa565b90505f610ecc610ec585676765c793fa10079d601b1b6113aa565b86906110fd565b610ef6907f00000000000000000000000000000000000000000000000000000000000000006113aa565b9050610f0282826110fd565b979650505050505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b179052610f67908590611116565b50505050565b5f6001600160ff1b03821115610f995760405163123baf0360e11b81526004810183905260240161048d565b5090565b5f818310610fc857604051631a065cf160e01b8152600481018490526024810183905260440161048d565b610fd283836113aa565b610fdd90600a611556565b610fe79085611393565b949350505050565b5f838302815f1985870982811083820303915050805f036110235783828161101957611019611424565b0492505050610e25565b8084116110435760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f806110bb868686610fef565b90506110c68361117c565b80156110e157505f84806110dc576110dc611424565b868809115b156110f4576110f16001826113bd565b90505b95945050505050565b5f610e2583676765c793fa10079d601b1b8460016110ae565b5f61112a6001600160a01b038416836111a8565b905080515f1415801561114e57508080602001905181019061114c9190611561565b155b1561117757604051635274afe760e01b81526001600160a01b038416600482015260240161048d565b505050565b5f600282600381111561119157611191611580565b61119b9190611594565b60ff166001149050919050565b6060610e2583835f845f80856001600160a01b031684866040516111cc91906115b5565b5f6040518083038185875af1925050503d805f8114611206576040519150601f19603f3d011682016040523d82523d5f602084013e61120b565b606091505b509150915061121b868383611225565b9695505050505050565b60608261123a5761123582611281565b610e25565b815115801561125157506001600160a01b0384163b155b1561127a57604051639996b31560e01b81526001600160a01b038516600482015260240161048d565b5080610e25565b8051156112915780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b803560ff811681146112ba575f80fd5b919050565b80356001600160a01b03811681146112ba575f80fd5b5f805f606084860312156112e7575f80fd5b6112f0846112aa565b92506112fe602085016112bf565b915061130c604085016112bf565b90509250925092565b5f8060408385031215611326575f80fd5b61132f836112aa565b915061133d602084016112bf565b90509250929050565b5f60208284031215611356575f80fd5b5051919050565b5f806040838503121561136e575f80fd5b505080516020909101519092909150565b634e487b7160e01b5f52601160045260245ffd5b8082028115828204841417610d6d57610d6d61137f565b81810381811115610d6d57610d6d61137f565b80820180821115610d6d57610d6d61137f565b5f600160ff1b82016113e4576113e461137f565b505f0390565b60ff9690961686526001600160a01b039485166020870152928416604086015292166060840152608083019190915260a082015260c00190565b634e487b7160e01b5f52601260045260245ffd5b5f8261144657611446611424565b500490565b5f8261145957611459611424565b500690565b5f6001820161146f5761146f61137f565b5060010190565b600181815b808511156114b057815f19048211156114965761149661137f565b808516156114a357918102915b93841c939080029061147b565b509250929050565b5f826114c657506001610d6d565b816114d257505f610d6d565b81600181146114e857600281146114f25761150e565b6001915050610d6d565b60ff8411156115035761150361137f565b50506001821b610d6d565b5060208310610133831016604e8410600b8410161715611531575081810a610d6d565b61153b8383611476565b805f190482111561154e5761154e61137f565b029392505050565b5f610e2583836114b8565b5f60208284031215611571575f80fd5b81518015158114610e25575f80fd5b634e487b7160e01b5f52602160045260245ffd5b5f60ff8316806115a6576115a6611424565b8060ff84160691505092915050565b5f82515f5b818110156115d457602081860181015185830152016115ba565b505f92019182525091905056fea2646970667358221220e91ed03f8fac5c7addb545ab474c9d79dbc2bfde466fe5fb939b94a50270e6d464736f6c6343000815003300000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f5000000000000000000000000e5a5f3a6c88b894710992e1c2626be0deb99566e00000000000000000000000039c66deaa7ba7576ed1498c5a0601454740e386c0000000000000000000000000000000000000000031a17e847807b1bc0000000000000000000000000000000000000000000000003e09de2596099e2b0000000000000000000000000000000000000000000000000084595161401484a000000000000000000000000000000000000000000000000a56fa5b99019a5c8000000
Deployed Bytecode
0x608060405234801561000f575f80fd5b506004361061009b575f3560e01c806391b9b8271161006357806391b9b8271461018e578063a0d5f599146101b5578063ae539533146101c8578063c5d664c6146101ef578063e349556914610216575f80fd5b80631f5155c41461009f57806325840eda146100e357806349ed64341461010b5780637535d2461461014057806390a8ae9b14610167575b5f80fd5b6100c67f00000000000000000000000039c66deaa7ba7576ed1498c5a0601454740e386c81565b6040516001600160a01b0390911681526020015b60405180910390f35b6100f66100f13660046112d5565b61023d565b604080519283526020830191909152016100da565b6101327f000000000000000000000000000000000000000000084595161401484a00000081565b6040519081526020016100da565b6100c67f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f581565b6101327f0000000000000000000000000000000000000000031a17e847807b1bc000000081565b6100c67f000000000000000000000000e5a5f3a6c88b894710992e1c2626be0deb99566e81565b6101326101c3366004611315565b6109d4565b6101327f000000000000000000000000000000000000000003e09de2596099e2b000000081565b6100c67f000000000000000000000000420000000000000000000000000000000000000681565b6101327f000000000000000000000000000000000000000000a56fa5b99019a5c800000081565b5f8061026c6040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b5f610275610d73565b90505f6102e7601283604001516001600160a01b031663a36849776040518163ffffffff1660e01b8152600401602060405180830381865afa1580156102bd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102e19190611346565b90610e18565b604051639a3db79b60e01b815260ff8a1660048201526001600160a01b0389811660248301529192505f9182917f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f590911690639a3db79b906044016040805180830381865afa15801561035c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610380919061135d565b604051633c04b54760e01b815260ff8d16600482015291935091505f906001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f51690633c04b54790602401602060405180830381865afa1580156103ec573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104109190611346565b9050835f036104325760405163150c57e560e01b815260040160405180910390fd5b84515f9061044a906104448787611393565b90610e2c565b90505f61046161045a8486611393565b8390610e43565b9050676765c793fa10079d601b1b811061049657604051630df91f7b60e11b8152600481018290526024015b60405180910390fd5b5f6104ac82676765c793fa10079d601b1b6113aa565b6104d6907f000000000000000000000000000000000000000000084595161401484a0000006113bd565b905087602001518111156104ee5787602001516104f0565b805b905061051161050a82676765c793fa10079d601b1b6113aa565b8890610e5a565b60808a015261052d6105238587611393565b8951859084610e73565b89525061053c90508284611393565b8751111561066e5760408701839052602087018490526001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f51663979397438d8d7f000000000000000000000000e5a5f3a6c88b894710992e1c2626be0deb99566e806105ae8a6113d0565b8d604001516105bc906113d0565b6040518763ffffffff1660e01b81526004016105dd969594939291906113ea565b5f604051808303815f87803b1580156105f4575f80fd5b505af1158015610606573d5f803e3d5ffd5b5050506040808901516020808b015183519283529082015260ff8f1692506001600160a01b038d169133917f54f9b006b19a44694e56b0d6a57f34c420bf88da7373f9d0f3380e5f4b70951e910160405180910390a45f8098509850505050505050506109cc565b604051638ba7650760e01b815260ff8d1660048201527f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f56001600160a01b031690638ba7650790602401602060405180830381865afa1580156106d3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106f79190611346565b87516107038486611393565b61070d91906113aa565b10156107495761071d8284611393565b87526040870183905260808701516107358385611393565b61073f9190611438565b60208801526107ab565b8651610756908390611438565b604088015286515f9061076a90849061144b565b11156107825786604001805161077f9061145e565b90525b608087015187516107939190611438565b602088015260408701516107a8908390611393565b87525b86515f906107c590676765c793fa10079d601b1b90611438565b90505f676765c793fa10079d601b1b895f01516107e2919061144b565b11156107f4576107f18161145e565b90505b6108296001600160a01b037f000000000000000000000000420000000000000000000000000000000000000616333084610f0d565b7f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f56001600160a01b031663979397438e8e8e306108698e60200151610f6d565b610872906113d0565b61087f8f60400151610f6d565b610888906113d0565b6040518763ffffffff1660e01b81526004016108a9969594939291906113ea565b5f604051808303815f87803b1580156108c0575f80fd5b505af11580156108d2573d5f803e3d5ffd5b50508951604051631b063dfb60e31b815230600482015260248101919091527f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f56001600160a01b0316925063d831efd891506044015f604051808303815f87803b15801561093e575f80fd5b505af1158015610950573d5f803e3d5ffd5b505050508c60ff168b6001600160a01b0316336001600160a01b03167f54f9b006b19a44694e56b0d6a57f34c420bf88da7373f9d0f3380e5f4b70951e8b604001518c602001516040516109ae929190918252602082015260400190565b60405180910390a4875f015188602001519950995050505050505050505b935093915050565b5f806109de610d73565b90505f610a26601283604001516001600160a01b031663a36849776040518163ffffffff1660e01b8152600401602060405180830381865afa1580156102bd573d5f803e3d5ffd5b604051639a3db79b60e01b815260ff871660048201526001600160a01b0386811660248301529192505f9182917f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f590911690639a3db79b906044016040805180830381865afa158015610a9b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610abf919061135d565b604051633c04b54760e01b815260ff8a16600482015291935091505f906001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f51690633c04b54790602401602060405180830381865afa158015610b2b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b4f9190611346565b9050835f03610b715760405163150c57e560e01b815260040160405180910390fd5b84515f90610b83906104448787611393565b90505f610b9361045a8486611393565b9050676765c793fa10079d601b1b8110610bc357604051630df91f7b60e11b81526004810182905260240161048d565b5f610bd982676765c793fa10079d601b1b6113aa565b610c03907f000000000000000000000000000000000000000000084595161401484a0000006113bd565b90508760200151811115610c1b578760200151610c1d565b805b90505f610c37610c2d8688611393565b8a51869085610e73565b9050610c438587611393565b811115610c5b575f9950505050505050505050610d6d565b604051638ba7650760e01b815260ff8d1660048201527f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f56001600160a01b031690638ba7650790602401602060405180830381865afa158015610cc0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ce49190611346565b81610cef8789611393565b610cf991906113aa565b1015610d0c57610d098587611393565b90505b5f610d22676765c793fa10079d601b1b8361144b565b11610d4157610d3c676765c793fa10079d601b1b82611438565b610d61565b610d56676765c793fa10079d601b1b82611438565b610d619060016113bd565b99505050505050505050505b92915050565b610d9d60405180606001604052805f81526020015f81526020015f6001600160a01b031681525090565b6001600160a01b037f00000000000000000000000039c66deaa7ba7576ed1498c5a0601454740e386c1660408201527f0000000000000000000000000000000000000000031a17e847807b1bc000000081527f000000000000000000000000000000000000000000a56fa5b99019a5c8000000602082015290565b5f610e258383601b610f9d565b9392505050565b5f610e258383676765c793fa10079d601b1b610fef565b5f610e2583676765c793fa10079d601b1b84610fef565b5f610e258383676765c793fa10079d601b1b60016110ae565b5f8084610ea0877f000000000000000000000000000000000000000003e09de2596099e2b0000000610e5a565b610eaa91906113aa565b90505f610ecc610ec585676765c793fa10079d601b1b6113aa565b86906110fd565b610ef6907f000000000000000000000000000000000000000003e09de2596099e2b00000006113aa565b9050610f0282826110fd565b979650505050505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b179052610f67908590611116565b50505050565b5f6001600160ff1b03821115610f995760405163123baf0360e11b81526004810183905260240161048d565b5090565b5f818310610fc857604051631a065cf160e01b8152600481018490526024810183905260440161048d565b610fd283836113aa565b610fdd90600a611556565b610fe79085611393565b949350505050565b5f838302815f1985870982811083820303915050805f036110235783828161101957611019611424565b0492505050610e25565b8084116110435760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f806110bb868686610fef565b90506110c68361117c565b80156110e157505f84806110dc576110dc611424565b868809115b156110f4576110f16001826113bd565b90505b95945050505050565b5f610e2583676765c793fa10079d601b1b8460016110ae565b5f61112a6001600160a01b038416836111a8565b905080515f1415801561114e57508080602001905181019061114c9190611561565b155b1561117757604051635274afe760e01b81526001600160a01b038416600482015260240161048d565b505050565b5f600282600381111561119157611191611580565b61119b9190611594565b60ff166001149050919050565b6060610e2583835f845f80856001600160a01b031684866040516111cc91906115b5565b5f6040518083038185875af1925050503d805f8114611206576040519150601f19603f3d011682016040523d82523d5f602084013e61120b565b606091505b509150915061121b868383611225565b9695505050505050565b60608261123a5761123582611281565b610e25565b815115801561125157506001600160a01b0384163b155b1561127a57604051639996b31560e01b81526001600160a01b038516600482015260240161048d565b5080610e25565b8051156112915780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b803560ff811681146112ba575f80fd5b919050565b80356001600160a01b03811681146112ba575f80fd5b5f805f606084860312156112e7575f80fd5b6112f0846112aa565b92506112fe602085016112bf565b915061130c604085016112bf565b90509250925092565b5f8060408385031215611326575f80fd5b61132f836112aa565b915061133d602084016112bf565b90509250929050565b5f60208284031215611356575f80fd5b5051919050565b5f806040838503121561136e575f80fd5b505080516020909101519092909150565b634e487b7160e01b5f52601160045260245ffd5b8082028115828204841417610d6d57610d6d61137f565b81810381811115610d6d57610d6d61137f565b80820180821115610d6d57610d6d61137f565b5f600160ff1b82016113e4576113e461137f565b505f0390565b60ff9690961686526001600160a01b039485166020870152928416604086015292166060840152608083019190915260a082015260c00190565b634e487b7160e01b5f52601260045260245ffd5b5f8261144657611446611424565b500490565b5f8261145957611459611424565b500690565b5f6001820161146f5761146f61137f565b5060010190565b600181815b808511156114b057815f19048211156114965761149661137f565b808516156114a357918102915b93841c939080029061147b565b509250929050565b5f826114c657506001610d6d565b816114d257505f610d6d565b81600181146114e857600281146114f25761150e565b6001915050610d6d565b60ff8411156115035761150361137f565b50506001821b610d6d565b5060208310610133831016604e8410600b8410161715611531575081810a610d6d565b61153b8383611476565b805f190482111561154e5761154e61137f565b029392505050565b5f610e2583836114b8565b5f60208284031215611571575f80fd5b81518015158114610e25575f80fd5b634e487b7160e01b5f52602160045260245ffd5b5f60ff8316806115a6576115a6611424565b8060ff84160691505092915050565b5f82515f5b818110156115d457602081860181015185830152016115ba565b505f92019182525091905056fea2646970667358221220e91ed03f8fac5c7addb545ab474c9d79dbc2bfde466fe5fb939b94a50270e6d464736f6c63430008150033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f5000000000000000000000000e5a5f3a6c88b894710992e1c2626be0deb99566e00000000000000000000000039c66deaa7ba7576ed1498c5a0601454740e386c0000000000000000000000000000000000000000031a17e847807b1bc0000000000000000000000000000000000000000000000003e09de2596099e2b0000000000000000000000000000000000000000000000000084595161401484a000000000000000000000000000000000000000000000000a56fa5b99019a5c8000000
-----Decoded View---------------
Arg [0] : _ionPool (address): 0x00000000000fA8e0FD26b4554d067CF1856De7F5
Arg [1] : _protocol (address): 0xE5a5F3A6C88B894710992e1C2626be0DEB99566E
Arg [2] : _reserveOracle (address): 0x39c66dEAA7BA7576ed1498C5A0601454740e386C
Arg [3] : _liquidationThreshold (uint256): 960000000000000000000000000
Arg [4] : _targetHealth (uint256): 1200000000000000000000000000
Arg [5] : _reserveFactor (uint256): 10000000000000000000000000
Arg [6] : _maxDiscount (uint256): 200000000000000000000000000
-----Encoded View---------------
7 Constructor Arguments found :
Arg [0] : 00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f5
Arg [1] : 000000000000000000000000e5a5f3a6c88b894710992e1c2626be0deb99566e
Arg [2] : 00000000000000000000000039c66deaa7ba7576ed1498c5a0601454740e386c
Arg [3] : 0000000000000000000000000000000000000000031a17e847807b1bc0000000
Arg [4] : 000000000000000000000000000000000000000003e09de2596099e2b0000000
Arg [5] : 000000000000000000000000000000000000000000084595161401484a000000
Arg [6] : 000000000000000000000000000000000000000000a56fa5b99019a5c8000000
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 33 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.