Source Code
Latest 22 from a total of 22 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Repay And Withdr... | 30793633 | 281 days ago | IN | 0 ETH | 0.00000042 | ||||
| Flash Deleverage... | 30793629 | 281 days ago | IN | 0 ETH | 0.0000009 | ||||
| Flash Deleverage... | 27776565 | 351 days ago | IN | 0 ETH | 0.00000143 | ||||
| Flash Leverage W... | 27776514 | 351 days ago | IN | 0 ETH | 0.00000166 | ||||
| Flash Deleverage... | 27718013 | 352 days ago | IN | 0 ETH | 0.00000268 | ||||
| Repay And Withdr... | 27679665 | 353 days ago | IN | 0 ETH | 0.00000082 | ||||
| Flash Deleverage... | 27679660 | 353 days ago | IN | 0 ETH | 0.00000176 | ||||
| Repay And Withdr... | 25518996 | 403 days ago | IN | 0 ETH | 0.00000365 | ||||
| Flash Deleverage... | 25518991 | 403 days ago | IN | 0 ETH | 0.00000765 | ||||
| Flash Leverage W... | 25517084 | 403 days ago | IN | 0 ETH | 0.00000881 | ||||
| Repay And Withdr... | 21334986 | 500 days ago | IN | 0 ETH | 0.00000086 | ||||
| Flash Deleverage... | 21334978 | 500 days ago | IN | 0 ETH | 0.00000183 | ||||
| Repay Full And W... | 20453127 | 521 days ago | IN | 0 ETH | 0.00000183 | ||||
| Flash Deleverage... | 20453001 | 521 days ago | IN | 0 ETH | 0.00000345 | ||||
| Flash Leverage W... | 20452921 | 521 days ago | IN | 0 ETH | 0.00000427 | ||||
| Flash Deleverage... | 19316684 | 547 days ago | IN | 0 ETH | 0.00000193 | ||||
| Flash Leverage W... | 19222400 | 549 days ago | IN | 0 ETH | 0.00000286 | ||||
| Flash Leverage W... | 19183445 | 550 days ago | IN | 0 ETH | 0.00000147 | ||||
| Flash Leverage W... | 19176643 | 550 days ago | IN | 0 ETH | 0.00000212 | ||||
| Flash Leverage W... | 19111527 | 552 days ago | IN | 0 ETH | 0.00000324 | ||||
| Flash Leverage W... | 19107915 | 552 days ago | IN | 0 ETH | 0.00000376 | ||||
| Flash Leverage W... | 19107833 | 552 days ago | IN | 0 ETH | 0.0000047 |
Latest 1 internal transaction
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 16878725 | 603 days ago | Contract Creation | 0 ETH |
Cross-Chain Transactions
Loading...
Loading
Contract Name:
WeEthWethHandler
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: BUSL-1.1
pragma solidity 0.8.21;
import { IonPool } from "../../IonPool.sol";
import { GemJoin } from "../../join/GemJoin.sol";
import { Whitelist } from "../../Whitelist.sol";
import { IonHandlerBase } from "../IonHandlerBase.sol";
import { UniswapFlashloanBalancerSwapHandler } from "./../UniswapFlashloanBalancerSwapHandler.sol";
import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import { IWETH9 } from "./../../interfaces/IWETH9.sol";
/**
* @notice Handler for the weETH collateral in the weETH/WETH market.
*
* @custom:security-contact [email protected]
*/
contract WeEthWethHandler is UniswapFlashloanBalancerSwapHandler {
/**
* @notice Creates a new `WeEthWethHandler` instance.
* @param _ilkIndex Ilk index of the pool.
* @param _ionPool address.
* @param _gemJoin address.
* @param _whitelist address.
* @param _wstEthUniswapPool address of the wstETH/WETH Uniswap pool
* @param _balancerPoolId Balancer pool ID for the weETH/WETH pool.
*/
constructor(
uint8 _ilkIndex,
IonPool _ionPool,
GemJoin _gemJoin,
Whitelist _whitelist,
IUniswapV3Pool _wstEthUniswapPool,
bytes32 _balancerPoolId,
IWETH9 _weth
)
IonHandlerBase(_ilkIndex, _ionPool, _gemJoin, _whitelist, _weth)
UniswapFlashloanBalancerSwapHandler(_wstEthUniswapPool, _balancerPoolId)
{ }
}// 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: AGPL-3.0-or-later
pragma solidity 0.8.21;
import { IonPool } from "../IonPool.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @notice Collateral deposits are held independently from the `IonPool` core
* contract, but credited to users through `gem` balances.
*
* @dev Separating collateral deposits from the core contract allows for
* handling tokens with non-standard behavior, if needed.
*
* This contract implements access control through `Ownable2Step`.
*
* This contract implements pausing through OpenZeppelin's `Pausable`.
*
* @custom:security-contact [email protected]
*/
contract GemJoin is Ownable2Step, Pausable {
error Int256Overflow();
error WrongIlkAddress(uint8 ilkIndex, IERC20 gem);
using SafeERC20 for IERC20;
IERC20 public immutable GEM;
IonPool public immutable POOL;
uint8 public immutable ILK_INDEX;
uint256 public totalGem;
/**
* @notice Creates a new `GemJoin` instance.
* @param _pool Address of the `IonPool` contract.
* @param _gem ERC20 collateral to be associated with this `GemJoin` instance.
* @param _ilkIndex of the associated collateral.
* @param owner Admin of the contract.
*/
constructor(IonPool _pool, IERC20 _gem, uint8 _ilkIndex, address owner) Ownable(owner) {
GEM = _gem;
POOL = _pool;
ILK_INDEX = _ilkIndex;
// Sanity check
if (_pool.getIlkAddress(_ilkIndex) != address(_gem)) revert WrongIlkAddress(_ilkIndex, _gem);
}
/**
* @notice Pauses the contract.
* @dev Pauses the contract.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev Unpauses the contract.
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Converts ERC20 token into gem (credit inside of the `IonPool`'s internal accounting).
* @dev Gem will be sourced from `msg.sender` and credited to `user`.
* @param user to credit the gem to.
* @param amount of gem to add. [WAD]
*/
function join(address user, uint256 amount) external whenNotPaused {
if (int256(amount) < 0) revert Int256Overflow();
totalGem += amount;
POOL.mintAndBurnGem(ILK_INDEX, user, int256(amount));
GEM.safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @notice Debits gem from the `IonPool`'s internal accounting and withdraws it into ERC20 token.
* @dev Gem will be debited from `msg.sender` and sent to `user`.
* @param user to send the withdrawn ERC20 tokens to.
* @param amount of gem to remove. [WAD]
*/
function exit(address user, uint256 amount) external whenNotPaused {
if (int256(amount) < 0) revert Int256Overflow();
totalGem -= amount;
POOL.mintAndBurnGem(ILK_INDEX, msg.sender, -int256(amount));
GEM.safeTransfer(user, amount);
}
}// 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: BUSL-1.1
pragma solidity 0.8.21;
import { IonPool } from "../IonPool.sol";
import { IWETH9 } from "../interfaces/IWETH9.sol";
import { GemJoin } from "../join/GemJoin.sol";
import { WadRayMath, RAY } from "../libraries/math/WadRayMath.sol";
import { Whitelist } from "../Whitelist.sol";
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @notice The base handler contract for simpler interactions with the `IonPool`
* core contract. It combines various individual interactions into one compound
* interaction to facilitate reaching user end-goals in atomic fashion.
*
* @dev To actually borrow from `IonPool`, a user must submit a "normalized" borrow
* amount. This contract is designed to be user-intuitive and, thus, allows a user
* to submit a standard desired borrow amount, which this contract will then
* convert into to the appropriate "normalized" borrow amount.
*
* @custom:security-contact [email protected]
*/
abstract contract IonHandlerBase {
using SafeERC20 for IERC20;
using SafeERC20 for IWETH9;
using WadRayMath for uint256;
error CannotSendEthToContract();
error FlashloanRepaymentTooExpensive(uint256 repaymentAmount, uint256 maxRepaymentAmount);
error TransactionDeadlineReached(uint256 deadline);
/**
* @notice Checks if the tx is being executed before the designated deadline
* for execution.
* @dev This is used to prevent txs that have sat in the mempool for too
* long from executing at unintended prices.
*/
modifier checkDeadline(uint256 deadline) {
if (deadline <= block.timestamp) revert TransactionDeadlineReached(deadline);
_;
}
/**
* @notice Checks if `msg.sender` is on the whitelist.
* @dev This contract will be on the `protocolControlledWhitelist`. As such,
* it will validate that users are on the whitelist itself and be able to
* bypass the whitelist check on `IonPool`.
* @param proof to validate the whitelist check.
*/
modifier onlyWhitelistedBorrowers(bytes32[] calldata proof) {
WHITELIST.isWhitelistedBorrower(ILK_INDEX, msg.sender, msg.sender, proof);
_;
}
/**
* @dev During conversion from borrow amount -> "normalized" borrow amount,"
* there is division required. In certain scenarios, it may be desirable to
* round up during division, in others, to round down. This enum allows a
* developer to indicate the rounding direction by describing the
* `amountToBorrow`. If it `IS_MIN`, then the final borrowed amount should
* be larger than `amountToBorrow` (round up), and vice versa for `IS_MAX`
* (round down).
*/
enum AmountToBorrow {
IS_MIN,
IS_MAX
}
IERC20 public immutable BASE;
IWETH9 public immutable WETH;
uint8 public immutable ILK_INDEX;
IonPool public immutable POOL;
GemJoin public immutable JOIN;
IERC20 public immutable LST_TOKEN;
Whitelist public immutable WHITELIST;
/**
* @notice Creates a new instance of `IonHandlerBase`
* @param _ilkIndex of the ilk for which this instance is associated with.
* @param _ionPool address of `IonPool` core contract.
* @param _gemJoin the `GemJoin` associated with the `ilkIndex` of this
* contract.
* @param _whitelist the `Whitelist` module address.
* @param _weth The WETH address of the chain.
*/
constructor(uint8 _ilkIndex, IonPool _ionPool, GemJoin _gemJoin, Whitelist _whitelist, IWETH9 _weth) {
POOL = _ionPool;
ILK_INDEX = _ilkIndex;
BASE = IERC20(_ionPool.underlying());
WETH = _weth;
address ilkAddress = POOL.getIlkAddress(_ilkIndex);
LST_TOKEN = IERC20(ilkAddress);
JOIN = _gemJoin;
WHITELIST = _whitelist;
BASE.approve(address(_ionPool), type(uint256).max);
IERC20(ilkAddress).approve(address(_gemJoin), type(uint256).max);
}
/**
* @notice Combines gem-joining and depositing collateral and then borrowing
* into one compound action.
* @param amountCollateral Amount of collateral to deposit. [WAD]
* @param amountToBorrow Amount of WETH to borrow. Due to rounding, true
* borrow amount might be slightly less. [WAD]
* @param proof that the user is whitelisted.
*/
function depositAndBorrow(
uint256 amountCollateral,
uint256 amountToBorrow,
bytes32[] calldata proof
)
external
onlyWhitelistedBorrowers(proof)
{
LST_TOKEN.safeTransferFrom(msg.sender, address(this), amountCollateral);
_depositAndBorrow(msg.sender, msg.sender, amountCollateral, amountToBorrow, AmountToBorrow.IS_MAX);
}
/**
* @notice Handles all logic to gem-join and deposit collateral, followed by
* a borrow. It is also possible to use this function simply to gem-join and
* deposit collateral atomically by setting `amountToBorrow` to 0.
* @param vaultHolder The user who will be responsible for repaying debt.
* @param receiver The user who receives the borrowed funds.
* @param amountCollateral to move into vault. [WAD]
* @param amountToBorrow out of the vault. [WAD]
* @param amountToBorrowType Whether the `amountToBorrow` is a min or max.
* This will dictate the rounding direction when converting to normalized
* amount. If it is a minimum, then the rounding will be rounded up. If it
* is a maximum, then the rounding will be rounded down.
*/
function _depositAndBorrow(
address vaultHolder,
address receiver,
uint256 amountCollateral,
uint256 amountToBorrow,
AmountToBorrow amountToBorrowType
)
internal
{
JOIN.join(address(this), amountCollateral);
POOL.depositCollateral(ILK_INDEX, vaultHolder, address(this), amountCollateral, new bytes32[](0));
if (amountToBorrow == 0) return;
uint256 rate = POOL.rate(ILK_INDEX);
uint256 normalizedAmountToBorrow;
if (amountToBorrowType == AmountToBorrow.IS_MIN) {
normalizedAmountToBorrow = amountToBorrow.rayDivUp(rate);
} else {
normalizedAmountToBorrow = amountToBorrow.rayDivDown(rate);
}
POOL.borrow(ILK_INDEX, vaultHolder, receiver, normalizedAmountToBorrow, new bytes32[](0));
}
/**
* @notice Will repay all debt and withdraw desired collateral amount. This
* function can also simply be used for a full repayment (which may be
* difficult through a direct tx to the `IonPool`) by setting
* `collateralToWithdraw` to 0.
* @dev Will repay the debt belonging to `msg.sender`. This function is
* necessary because with `rate` updating every single block, it may be
* difficult to repay a full amount if a user uses the total debt from a
* previous block. If a user ends up repaying all but dust amounts of debt
* (due to a slight `rate` change), then they repayment will likely fail due
* to the `dust` parameter.
* @param collateralToWithdraw in collateral terms. [WAD]
*/
function repayFullAndWithdraw(uint256 collateralToWithdraw) external {
(uint256 repayAmount, uint256 normalizedDebtToRepay) = _getFullRepayAmount(msg.sender);
BASE.safeTransferFrom(msg.sender, address(this), repayAmount);
POOL.repay(ILK_INDEX, msg.sender, address(this), normalizedDebtToRepay);
POOL.withdrawCollateral(ILK_INDEX, msg.sender, address(this), collateralToWithdraw);
JOIN.exit(msg.sender, collateralToWithdraw);
}
/**
* @notice Helper function to get the repayment amount for all the debt of a
* `user`.
* @dev This simply emulates the rounding behaviour of the `IonPool` to
* arrive at an accurate value.
* @param user Address of the user.
* @return repayAmount Amount of base asset required to repay all debt (this
* mimics IonPool's behavior). [WAD]
* @return normalizedDebt Total normalized debt held by `user`'s vault.
* [WAD]
*/
function _getFullRepayAmount(address user) internal view returns (uint256 repayAmount, uint256 normalizedDebt) {
uint256 currentRate = POOL.rate(ILK_INDEX);
normalizedDebt = POOL.normalizedDebt(ILK_INDEX, user);
// This is exactly how IonPool calculates the amount of base asset
// required
uint256 amountRad = normalizedDebt * currentRate;
repayAmount = amountRad / RAY;
if (amountRad % RAY > 0) ++repayAmount;
}
/**
* @notice Combines repaying debt and then withdrawing and gem-exitting
* collateral into one compound action.
*
* If repaying **all** is the intention, use `repayFullAndWithdraw()`
* instead to prevent tx revert from dust amounts of debt in vault.
* @param debtToRepay In ETH terms. [WAD]
* @param collateralToWithdraw In collateral terms. [WAD]
*/
function repayAndWithdraw(uint256 debtToRepay, uint256 collateralToWithdraw) external {
BASE.safeTransferFrom(msg.sender, address(this), debtToRepay);
_repayAndWithdraw(msg.sender, msg.sender, collateralToWithdraw, debtToRepay);
}
/**
* @notice Handles all logic to repay debt, followed by a collateral
* withdrawal and gem-exit. This function can also be used to just withdraw
* and gem-exit in atomic fashion by setting the `debtToRepay` to 0.
* @param vaultHolder The user whose debt will be repaid.
* @param receiver The user who receives the the withdrawn collateral.
* @param collateralToWithdraw to move into vault. [WAD]
* @param debtToRepay out of the vault. [WAD]
*/
function _repayAndWithdraw(
address vaultHolder,
address receiver,
uint256 collateralToWithdraw,
uint256 debtToRepay
)
internal
{
uint256 currentRate = POOL.rate(ILK_INDEX);
uint256 normalizedDebtToRepay = debtToRepay.rayDivDown(currentRate);
POOL.repay(ILK_INDEX, vaultHolder, address(this), normalizedDebtToRepay);
POOL.withdrawCollateral(ILK_INDEX, vaultHolder, address(this), collateralToWithdraw);
JOIN.exit(receiver, collateralToWithdraw);
}
/**
* @notice ETH cannot be directly sent to this contract.
* @dev To allow unwrapping of WETH into ETH.
*/
receive() external payable {
if (msg.sender != address(WETH)) revert CannotSendEthToContract();
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;
import { IWETH9 } from "../interfaces/IWETH9.sol";
import { IonHandlerBase } from "./IonHandlerBase.sol";
import { IWETH9 } from "../interfaces/IWETH9.sol";
import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import { IUniswapV3FlashCallback } from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3FlashCallback.sol";
import { IVault } from "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import { IAsset } from "@balancer-labs/v2-interfaces/contracts/vault/IAsset.sol";
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @notice This contract allows for easy creation and closing of leverage
* positions through Uniswap flashloans and LST swaps on Balancer. In terms of
* creation, this may be a more desirable path than directly minting from an LST
* provider since market prices tend to be slightly lower than provider exchange
* rates. DEXes also provide an avenue for atomic deleveraging since the LST ->
* ETH exchange can be made.
*
* This contract is used when the Balancer has a collateral asset <> base asset
* pool, and the Uniswap has a base asset flashloan.
*
* NOTE: Uniswap flashloans do charge a small fee.
*
* @dev Some tokens only have liquidity on Balancer. Due to the reentrancy lock
* on the Balancer VAULT, utilizing their free flashloan followed by a pool swap
* is not possible. Instead, we will take a cheap (0.01%) flashloan from the
* wstETH/ETH uniswap pool and perform the Balancer swap. The rETH/ETH uniswap
* pool could also be used since it has a 0.01% fee but it does have less
* liquidity.
*
* @custom:security-contact [email protected]
*/
abstract contract UniswapFlashloanBalancerSwapHandler is IUniswapV3FlashCallback, IonHandlerBase {
using SafeERC20 for IERC20;
using SafeERC20 for IWETH9;
error WethNotInPoolPair(IUniswapV3Pool pool);
error ReceiveCallerNotPool(address unauthorizedCaller);
IVault internal constant VAULT = IVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8);
bool immutable WETH_IS_TOKEN0_ON_UNISWAP;
IUniswapV3Pool public immutable FLASHLOAN_POOL;
bytes32 public immutable BALANCER_POOL_ID;
/**
* @notice Creates a new instance of `UniswapFlashloanBalancerSwapHandler`
* @param _flashloanPool UniswapV3 pool from which to flashloan
* @param _balancerPoolId Balancer pool identifier through which to route
* swaps.
*/
constructor(IUniswapV3Pool _flashloanPool, bytes32 _balancerPoolId) {
BASE.approve(address(VAULT), type(uint256).max);
IERC20(address(LST_TOKEN)).approve(address(VAULT), type(uint256).max);
FLASHLOAN_POOL = _flashloanPool;
address token0 = IUniswapV3Pool(_flashloanPool).token0();
address token1 = IUniswapV3Pool(_flashloanPool).token1();
// The naming convention uses `_weth`, but this terminology refers to
// the `BASE` token of the underlying IonPool.
bool _wethIsToken0 = token0 == address(BASE);
bool _wethIsToken1 = token1 == address(BASE);
if (!_wethIsToken0 && !_wethIsToken1) revert WethNotInPoolPair(_flashloanPool);
// Technically possible here for both tokens to be weth, but Uniswap does not allow for this
WETH_IS_TOKEN0_ON_UNISWAP = _wethIsToken0;
BALANCER_POOL_ID = _balancerPoolId;
}
/**
* @notice Transfer collateral from user + flashloan WETH from Uniswap ->
* swap for collateral using WETH on Balancer pool -> deposit all collateral
* into `IonPool` -> borrow WETH from `IonPool` -> repay Uniswap flashloan + fee.
*
* Uniswap flashloans do incur a fee.
*
* @param initialDeposit in collateral terms. [WAD]
* @param resultingAdditionalCollateral in collateral terms. [WAD]
* @param maxResultingAdditionalDebt in WETH terms. This value also allows
* the user to control slippage of the swap. [WAD]
* @param deadline timestamp for which the transaction must be executed.
* This prevents txs that have sat in the mempool for too long to be
* executed.
* @param proof used to validate the user is whitelisted.
*/
function flashLeverageWethAndSwap(
uint256 initialDeposit,
uint256 resultingAdditionalCollateral,
uint256 maxResultingAdditionalDebt,
uint256 deadline,
bytes32[] calldata proof
)
external
payable
checkDeadline(deadline)
onlyWhitelistedBorrowers(proof)
{
LST_TOKEN.safeTransferFrom(msg.sender, address(this), initialDeposit);
uint256 amountToLeverage = resultingAdditionalCollateral - initialDeposit;
if (amountToLeverage == 0) {
// AmountToBorrow.IS_MAX because we don't want to create any new debt here
_depositAndBorrow(msg.sender, address(this), resultingAdditionalCollateral, 0, AmountToBorrow.IS_MAX);
return;
}
FlashCallbackData memory flashCallbackData;
IVault.FundManagement memory fundManagement = IVault.FundManagement({
sender: address(this),
fromInternalBalance: false,
recipient: payable(this),
toInternalBalance: false
});
// We need to know how much weth we will need to pay for our desired
// amount of collateral output. Once we know this value, we can request
// the value from the flashloan.
uint256 wethIn = _simulateGivenOutBalancerSwap({
fundManagement: fundManagement,
assetIn: address(BASE),
assetOut: address(LST_TOKEN),
amountOut: amountToLeverage
});
flashCallbackData.user = msg.sender;
flashCallbackData.initialDeposit = initialDeposit;
flashCallbackData.maxResultingAdditionalDebtOrCollateralToRemove = maxResultingAdditionalDebt;
flashCallbackData.wethFlashloaned = wethIn;
flashCallbackData.amountToLeverage = amountToLeverage;
uint256 amount0ToFlash;
uint256 amount1ToFlash;
if (WETH_IS_TOKEN0_ON_UNISWAP) amount0ToFlash = wethIn;
else amount1ToFlash = wethIn;
FLASHLOAN_POOL.flash(address(this), amount0ToFlash, amount1ToFlash, abi.encode(flashCallbackData));
}
/**
* @notice Flashloan WETH from Uniswap -> repay debt in `IonPool` ->
* withdraw collateral from `IonPool` -> sell collateral for `WETH` on
* Balancer -> repay Uniswap flashloan + fee.
*
* Uniswap flashloans do incur a fee.
*
* @param maxCollateralToRemove The max amount of collateral user is willing
* to sell to repay `debtToRemove` debt. [WAD]
* @param debtToRemove The desired amount of debt to remove. [WAD]
* @param deadline timestamp for which the transaction must be executed.
* This prevents txs that have sat in the mempool for too long to be
* executed.
*/
function flashDeleverageWethAndSwap(
uint256 maxCollateralToRemove,
uint256 debtToRemove,
uint256 deadline
)
external
checkDeadline(deadline)
{
if (debtToRemove == type(uint256).max) {
(debtToRemove,) = _getFullRepayAmount(msg.sender);
}
if (debtToRemove == 0) return;
uint256 amount0ToFlash;
uint256 amount1ToFlash;
if (WETH_IS_TOKEN0_ON_UNISWAP) amount0ToFlash = debtToRemove;
else amount1ToFlash = debtToRemove;
FLASHLOAN_POOL.flash(
address(this),
amount0ToFlash,
amount1ToFlash,
abi.encode(
FlashCallbackData({
user: msg.sender,
initialDeposit: 0,
maxResultingAdditionalDebtOrCollateralToRemove: maxCollateralToRemove,
wethFlashloaned: debtToRemove,
amountToLeverage: 0
})
)
);
}
struct FlashCallbackData {
address user;
// This value is only used when leveraging
uint256 initialDeposit;
// This value will change its meaning depending on the direction of the
// swap. For leveraging, it is the max resulting additional debt. For
// deleveraging, it is the max collateral to remove.
uint256 maxResultingAdditionalDebtOrCollateralToRemove;
// How much weth was flashloaned from Uniswap. During leveraging this
// weth will be used to swap for collateral, and during deleveraging
// this weth will be used to repay IonPool debt.
uint256 wethFlashloaned;
// This value indicates the amount of extra collateral that must be
// borrowed. However, this value is only relevant for leveraging. If
// this value is zero, then we are deleveraging.
uint256 amountToLeverage;
}
/**
* @notice Called to `msg.sender` after transferring to the recipient from
* IUniswapV3Pool#flash.
*
* @dev In the implementation, you must repay the pool the tokens sent by
* `flash()` plus the computed fee amounts.
*
* The caller of this method must be checked to be a UniswapV3Pool.
*
* Initiator is guaranteed to be this contract since UniswapV3 pools will
* only call the callback on msg.sender.
*
* @param fee0 The fee amount in tokenInBalancer due to the pool by the end
* of the flash
* @param fee1 The fee amount in tokenOutBalancer due to the pool by the end
* of the flash
* @param data Any data passed through by the caller via the
* IUniswapV3PoolActions#flash call
*/
function uniswapV3FlashCallback(uint256 fee0, uint256 fee1, bytes calldata data) external override {
if (msg.sender != address(FLASHLOAN_POOL)) revert ReceiveCallerNotPool(msg.sender);
FlashCallbackData memory flashCallbackData = abi.decode(data, (FlashCallbackData));
IVault.FundManagement memory fundManagement = IVault.FundManagement({
sender: address(this),
fromInternalBalance: false,
recipient: payable(this),
toInternalBalance: false
});
uint256 fee = fee0 + fee1; // At least one of these should be zero, assuming only one token was flashloaned
if (flashCallbackData.amountToLeverage > 0) {
uint256 amountToLeverage = flashCallbackData.amountToLeverage;
address user = flashCallbackData.user;
uint256 maxResultingAdditionalDebt = flashCallbackData.maxResultingAdditionalDebtOrCollateralToRemove;
uint256 wethFlashloaned = flashCallbackData.wethFlashloaned;
uint256 wethToRepay = wethFlashloaned + fee;
if (wethToRepay > maxResultingAdditionalDebt) {
revert FlashloanRepaymentTooExpensive(wethToRepay, maxResultingAdditionalDebt);
}
IVault.SingleSwap memory balancerSwap = IVault.SingleSwap({
poolId: bytes32(BALANCER_POOL_ID),
kind: IVault.SwapKind.GIVEN_OUT,
assetIn: IAsset(address(BASE)),
assetOut: IAsset(address(LST_TOKEN)),
amount: amountToLeverage,
userData: ""
});
// We will skip slippage control for this step. This is OK since if
// there was a frontrun attack or the slippage is too high, then the
// `wethToRepay` value will go above the user's desired
// `maxResultingAdditionalDebt`
uint256 wethSent = VAULT.swap(balancerSwap, fundManagement, type(uint256).max, block.timestamp + 1);
// Sanity check
assert(wethSent == flashCallbackData.wethFlashloaned);
uint256 totalCollateral = flashCallbackData.initialDeposit + amountToLeverage;
_depositAndBorrow(user, address(this), totalCollateral, wethToRepay, AmountToBorrow.IS_MIN);
BASE.safeTransfer(msg.sender, wethToRepay);
} else {
// When deleveraging
uint256 totalRepayment = flashCallbackData.wethFlashloaned + fee;
uint256 collateralIn = _simulateGivenOutBalancerSwap({
fundManagement: fundManagement,
assetIn: address(LST_TOKEN),
assetOut: address(BASE),
amountOut: totalRepayment
});
uint256 maxCollateralToRemove = flashCallbackData.maxResultingAdditionalDebtOrCollateralToRemove;
if (collateralIn > maxCollateralToRemove) {
revert FlashloanRepaymentTooExpensive(collateralIn, maxCollateralToRemove);
}
_repayAndWithdraw(flashCallbackData.user, address(this), collateralIn, flashCallbackData.wethFlashloaned);
IVault.SingleSwap memory balancerSwap = IVault.SingleSwap({
poolId: bytes32(BALANCER_POOL_ID),
kind: IVault.SwapKind.GIVEN_OUT,
assetIn: IAsset(address(LST_TOKEN)),
assetOut: IAsset(address(BASE)),
amount: totalRepayment,
userData: ""
});
VAULT.swap(balancerSwap, fundManagement, type(uint256).max, block.timestamp + 1);
BASE.safeTransfer(msg.sender, totalRepayment);
}
}
function simulateGivenOutBalancerSwap(
IVault.FundManagement memory fundManagement,
address assetIn,
address assetOut,
uint256 amountOut
)
external
returns (uint256)
{
return _simulateGivenOutBalancerSwap(fundManagement, assetIn, assetOut, amountOut);
}
/**
* @notice Simulates a Balancer swap with a desired amount of `assetOut`.
* @param fundManagement Balancer fund management struct
* @param assetIn asset to swap from
* @param assetOut asset to swap to
* @param amountOut desired amount of assetOut. Will revert if not received. [WAD]
* @return Amount of input asset required to receive `amountOut`.
*/
function _simulateGivenOutBalancerSwap(
IVault.FundManagement memory fundManagement,
address assetIn,
address assetOut,
uint256 amountOut
)
internal
returns (uint256)
{
uint256 assetInIndex = 0;
uint256 assetOutIndex = 1;
IVault.BatchSwapStep memory swapStep = IVault.BatchSwapStep({
poolId: bytes32(BALANCER_POOL_ID),
assetInIndex: assetInIndex,
assetOutIndex: assetOutIndex,
amount: amountOut,
userData: ""
});
IAsset[] memory assets = new IAsset[](2);
assets[assetInIndex] = IAsset(assetIn);
assets[assetOutIndex] = IAsset(assetOut);
IVault.BatchSwapStep[] memory swapSteps = new IVault.BatchSwapStep[](1);
swapSteps[0] = swapStep;
return uint256(VAULT.queryBatchSwap(IVault.SwapKind.GIVEN_OUT, swapSteps, assets, fundManagement)[assetInIndex]);
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev WETH9 interface
*/
interface IWETH9 is IERC20 {
/**
* @dev Deposit ether to get wrapped ether
*/
function deposit() external payable;
/**
* @dev Withdraw wrapped ether to get ether
* @param amount Amount of wrapped ether to withdraw
*/
function withdraw(uint256 amount) external;
}// 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: 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
// 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: 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: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.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 Pausable is Context {
bool private _paused;
/**
* @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.
*/
constructor() {
_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) {
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 {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}// 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) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#flash
/// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface
interface IUniswapV3FlashCallback {
/// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.
/// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param fee0 The fee amount in token0 due to the pool by the end of the flash
/// @param fee1 The fee amount in token1 due to the pool by the end of the flash
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call
function uniswapV3FlashCallback(
uint256 fee0,
uint256 fee1,
bytes calldata data
) external;
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "../solidity-utils/openzeppelin/IERC20.sol";
import "../solidity-utils/helpers/IAuthentication.sol";
import "../solidity-utils/helpers/ISignaturesValidator.sol";
import "../solidity-utils/helpers/ITemporarilyPausable.sol";
import "../solidity-utils/misc/IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "./IProtocolFeesCollector.sol";
pragma solidity >=0.7.0 <0.9.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable, IAuthentication {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (IProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}// 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/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) (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) (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
pragma solidity >=0.7.0 <0.9.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @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);
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
import "../openzeppelin/IERC20.sol";
/**
* @dev Interface for WETH9.
* See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "../solidity-utils/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
pragma experimental ABIEncoderV2;
import "../solidity-utils/openzeppelin/IERC20.sol";
import "./IVault.sol";
import "./IAuthorizer.sol";
interface IProtocolFeesCollector {
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external;
function setSwapFeePercentage(uint256 newSwapFeePercentage) external;
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external;
function getSwapFeePercentage() external view returns (uint256);
function getFlashLoanFeePercentage() external view returns (uint256);
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts);
function getAuthorizer() external view returns (IAuthorizer);
function vault() external view returns (IVault);
}// 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) (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":"uint8","name":"_ilkIndex","type":"uint8"},{"internalType":"contract IonPool","name":"_ionPool","type":"address"},{"internalType":"contract GemJoin","name":"_gemJoin","type":"address"},{"internalType":"contract Whitelist","name":"_whitelist","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"_wstEthUniswapPool","type":"address"},{"internalType":"bytes32","name":"_balancerPoolId","type":"bytes32"},{"internalType":"contract IWETH9","name":"_weth","type":"address"}],"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":"CannotSendEthToContract","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"uint256","name":"repaymentAmount","type":"uint256"},{"internalType":"uint256","name":"maxRepaymentAmount","type":"uint256"}],"name":"FlashloanRepaymentTooExpensive","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[{"internalType":"address","name":"unauthorizedCaller","type":"address"}],"name":"ReceiveCallerNotPool","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"TransactionDeadlineReached","type":"error"},{"inputs":[{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"}],"name":"WethNotInPoolPair","type":"error"},{"inputs":[],"name":"BALANCER_POOL_ID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BASE","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FLASHLOAN_POOL","outputs":[{"internalType":"contract IUniswapV3Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ILK_INDEX","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"JOIN","outputs":[{"internalType":"contract GemJoin","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LST_TOKEN","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL","outputs":[{"internalType":"contract IonPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"contract IWETH9","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WHITELIST","outputs":[{"internalType":"contract Whitelist","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountCollateral","type":"uint256"},{"internalType":"uint256","name":"amountToBorrow","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"depositAndBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"maxCollateralToRemove","type":"uint256"},{"internalType":"uint256","name":"debtToRemove","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"flashDeleverageWethAndSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"initialDeposit","type":"uint256"},{"internalType":"uint256","name":"resultingAdditionalCollateral","type":"uint256"},{"internalType":"uint256","name":"maxResultingAdditionalDebt","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"flashLeverageWethAndSwap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"debtToRepay","type":"uint256"},{"internalType":"uint256","name":"collateralToWithdraw","type":"uint256"}],"name":"repayAndWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"collateralToWithdraw","type":"uint256"}],"name":"repayFullAndWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"bool","name":"fromInternalBalance","type":"bool"},{"internalType":"address payable","name":"recipient","type":"address"},{"internalType":"bool","name":"toInternalBalance","type":"bool"}],"internalType":"struct IVault.FundManagement","name":"fundManagement","type":"tuple"},{"internalType":"address","name":"assetIn","type":"address"},{"internalType":"address","name":"assetOut","type":"address"},{"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"simulateGivenOutBalancerSwap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee0","type":"uint256"},{"internalType":"uint256","name":"fee1","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"uniswapV3FlashCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]Contract Creation Code
6101c060405234801562000011575f80fd5b5060405162002df238038062002df28339810160408190526200003491620004d7565b82828888888886836001600160a01b031660e0816001600160a01b0316815250508460ff1660c08160ff1681525050836001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa158015620000a0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620000c6919062000575565b6001600160a01b0390811660805281811660a05260e05160405163efff005f60e01b815260ff881660048201525f92919091169063efff005f90602401602060405180830381865afa1580156200011f573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000145919062000575565b6001600160a01b0381811661012052858116610100528481166101405260805160405163095ea7b360e01b815288831660048201525f196024820152929350169063095ea7b3906044016020604051808303815f875af1158015620001ac573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620001d291906200059a565b5060405163095ea7b360e01b81526001600160a01b0385811660048301525f19602483015282169063095ea7b3906044016020604051808303815f875af115801562000220573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200024691906200059a565b505060805160405163095ea7b360e01b815273ba12222222228d8ba445958a75a0704d566bf2c860048201525f1960248201526001600160a01b03909116955063095ea7b3945060440192506200029b915050565b6020604051808303815f875af1158015620002b8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620002de91906200059a565b506101205160405163095ea7b360e01b815273ba12222222228d8ba445958a75a0704d566bf2c860048201525f1960248201526001600160a01b039091169063095ea7b3906044016020604051808303815f875af115801562000343573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200036991906200059a565b50816001600160a01b0316610180816001600160a01b0316815250505f826001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015620003c3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620003e9919062000575565b90505f836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000429573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200044f919062000575565b6080519091506001600160a01b0390811683821681149183161481158262000475575080155b15620004a357604051633f42eb2d60e01b81526001600160a01b038716600482015260240160405180910390fd5b5015156101605250506101a05250620005bb9650505050505050565b6001600160a01b0381168114620004d4575f80fd5b50565b5f805f805f805f60e0888a031215620004ee575f80fd5b875160ff81168114620004ff575f80fd5b60208901519097506200051281620004bf565b60408901519096506200052581620004bf565b60608901519095506200053881620004bf565b60808901519094506200054b81620004bf565b60a089015160c08a015191945092506200056581620004bf565b8091505092959891949750929550565b5f6020828403121562000586575f80fd5b81516200059381620004bf565b9392505050565b5f60208284031215620005ab575f80fd5b8151801515811462000593575f80fd5b60805160a05160c05160e05161010051610120516101405161016051610180516101a051612670620007825f395f818161031001528181610c4a01528181610ead01526113e201525f81816103f901528181610651015281816107730152610b6c01525f8181610620015261074201525f818161018901528181610448015261084b01525f81816101d901528181610507015281816105d60152818161090a01528181610ca901528181610e140152610edd01525f818161023f01528181610afb015281816110f001526119ea01525f818161020c015281816109ba01528181610a57015281816111570152818161125e0152818161131201528181611621015281816116d5015281816118070152818161189f015261193c01525f81816103b4015281816104770152818161087a015281816109e701528181610a86015281816111820152818161123501528181611339015281816115ec0152818161169b015281816117de015281816118cc015261196b01525f818161010201526102be01525f8181610381015281816105b50152818161097b01528181610c7a01528181610dc601528181610e3501528181610f0c01528181610ff4015261103501526126705ff3fe6080604052600436106100f2575f3560e01c8063ad5c464811610087578063ebc9b94d11610057578063ebc9b94d14610351578063ec342ad014610370578063ed0cee97146103a3578063f676c6a4146103e8575f80fd5b8063ad5c4648146102ad578063e54a55b6146102e0578063e7f6d7c4146102ff578063e9cbafb014610332575f80fd5b80637535d246116100c25780637535d246146101fb5780637f9681481461022e57806396c7525914610261578063aac56b5814610280575f80fd5b80630cc20584146101465780630eb3e108146101595780631bb7cc991461017857806350c6cf88146101c8575f80fd5b3661014257336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461014057604051637c56635360e01b815260040160405180910390fd5b005b5f80fd5b610140610154366004611d5c565b61041b565b348015610164575f80fd5b50610140610173366004611dc1565b6106ff565b348015610183575f80fd5b506101ab7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156101d3575f80fd5b506101ab7f000000000000000000000000000000000000000000000000000000000000000081565b348015610206575f80fd5b506101ab7f000000000000000000000000000000000000000000000000000000000000000081565b348015610239575f80fd5b506101ab7f000000000000000000000000000000000000000000000000000000000000000081565b34801561026c575f80fd5b5061014061027b366004611dea565b610847565b34801561028b575f80fd5b5061029f61029a366004611eaf565b610948565b6040519081526020016101bf565b3480156102b8575f80fd5b506101ab7f000000000000000000000000000000000000000000000000000000000000000081565b3480156102eb575f80fd5b506101406102fa366004611f6b565b61095e565b34801561030a575f80fd5b5061029f7f000000000000000000000000000000000000000000000000000000000000000081565b34801561033d575f80fd5b5061014061034c366004611f82565b610b61565b34801561035c575f80fd5b5061014061036b366004611ffb565b611028565b34801561037b575f80fd5b506101ab7f000000000000000000000000000000000000000000000000000000000000000081565b3480156103ae575f80fd5b506103d67f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff90911681526020016101bf565b3480156103f3575f80fd5b506101ab7f000000000000000000000000000000000000000000000000000000000000000081565b824281116104445760405163356dfb6f60e01b8152600481018290526024015b60405180910390fd5b82827f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b5406b3d7f0000000000000000000000000000000000000000000000000000000000000000333386866040518663ffffffff1660e01b81526004016104ba95949392919061201b565b602060405180830381865afa1580156104d5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104f99190612076565b5061052f6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308c61106d565b5f61053a8a8a6120a5565b9050805f036105575761055133308b5f60016110d4565b506106f4565b61058d6040518060a001604052805f6001600160a01b031681526020015f81526020015f81526020015f81526020015f81525090565b60408051608081018252308082525f602083018190529282015260608101829052906105fb827f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000876113d6565b338452602084018e9052604084018c9052606084018190526080840185905290505f807f00000000000000000000000000000000000000000000000000000000000000001561064c5782915061064f565b50815b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663490e6cbc3084848960405160200161069291906120b8565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016106c09493929190612143565b5f604051808303815f87803b1580156106d7575f80fd5b505af11580156106e9573d5f803e3d5ffd5b505050505050505050505b505050505050505050565b804281116107235760405163356dfb6f60e01b81526004810182905260240161043b565b5f19830361073857610734336115db565b5092505b8215610841575f807f00000000000000000000000000000000000000000000000000000000000000001561076e57849150610771565b50835b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663490e6cbc3084846040518060a00160405280336001600160a01b031681526020015f81526020018c81526020018b81526020015f8152506040516020016107e391906120b8565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016108119493929190612143565b5f604051808303815f87803b158015610828575f80fd5b505af115801561083a573d5f803e3d5ffd5b5050505050505b50505050565b81817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b5406b3d7f0000000000000000000000000000000000000000000000000000000000000000333386866040518663ffffffff1660e01b81526004016108bd95949392919061201b565b602060405180830381865afa1580156108d8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108fc9190612076565b506109326001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308961106d565b6109403333888860016110d4565b505050505050565b5f610955858585856113d6565b95945050505050565b5f80610969336115db565b90925090506109a36001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308561106d565b604051638459b43760e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690638459b43790610a15907f00000000000000000000000000000000000000000000000000000000000000009033903090879060040161216f565b5f604051808303815f87803b158015610a2c575f80fd5b505af1158015610a3e573d5f803e3d5ffd5b5050604051631d0fe70360e21b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016925063743f9c0c9150610ab4907f00000000000000000000000000000000000000000000000000000000000000009033903090899060040161216f565b5f604051808303815f87803b158015610acb575f80fd5b505af1158015610add573d5f803e3d5ffd5b505060405163ef693bed60e01b8152336004820152602481018690527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316925063ef693bed91506044015f604051808303815f87803b158015610b46575f80fd5b505af1158015610b58573d5f803e3d5ffd5b50505050505050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610bac57604051634c04358d60e11b815233600482015260240161043b565b5f610bb982840184612199565b60408051608081018252308082525f602083018190529282015260608101829052919250610be78688612210565b608084015190915015610dfa5760808301518351604085015160608601515f610c108683612210565b905082811115610c3d57604051634245776b60e11b8152600481018290526024810184905260440161043b565b6040805160c081019091527f000000000000000000000000000000000000000000000000000000000000000081525f9060208101600181526020017f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031681526020017f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316815260200187815260200160405180602001604052805f81525081525090505f73ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b03166352bbbe29838b5f19426001610d259190612210565b6040518563ffffffff1660e01b8152600401610d449493929190612257565b6020604051808303815f875af1158015610d60573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d849190612311565b905089606001518114610d9957610d99612328565b5f878b60200151610daa9190612210565b9050610db9873083875f6110d4565b610ded6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163386611797565b5050505050505050610b58565b5f818460600151610e0b9190612210565b90505f610e5a847f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000856113d6565b604086015190915080821115610e8d57604051634245776b60e11b8152600481018390526024810182905260440161043b565b610ea0865f0151308489606001516117cd565b6040805160c081019091527f000000000000000000000000000000000000000000000000000000000000000081525f9060208101600181526020017f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031681526020017f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316815260200185815260200160405180602001604052805f815250815250905073ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b03166352bbbe2982885f19426001610f879190612210565b6040518563ffffffff1660e01b8152600401610fa69493929190612257565b6020604051808303815f875af1158015610fc2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fe69190612311565b5061101b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163386611797565b5050505050505050505050565b61105d6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308561106d565b611069333383856117cd565b5050565b6040516001600160a01b0384811660248301528381166044830152606482018390526108419186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611a1b565b604051633b4da69f60e01b8152306004820152602481018490527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690633b4da69f906044015f604051808303815f87803b158015611139575f80fd5b505af115801561114b573d5f803e3d5ffd5b50506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016915063918a2f4290507f00000000000000000000000000000000000000000000000000000000000000008730875f6040519080825280602002602001820160405280156111ce578160200160208202803683370190505b506040518663ffffffff1660e01b81526004016111ef95949392919061233c565b5f604051808303815f87803b158015611206575f80fd5b505af1158015611218573d5f803e3d5ffd5b50505050815f03156113cf57604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690633c04b54790602401602060405180830381865afa1580156112ab573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112cf9190612311565b90505f808360018111156112e5576112e5612223565b036112fb576112f48483611a7c565b9050611308565b6113058483611a9f565b90505b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016639306f2f87f00000000000000000000000000000000000000000000000000000000000000008989855f604051908082528060200260200182016040528015611385578160200160208202803683370190505b506040518663ffffffff1660e01b81526004016113a695949392919061233c565b5f604051808303815f87803b1580156113bd575f80fd5b505af115801561101b573d5f803e3d5ffd5b5050505050565b6040805160a0810182527f000000000000000000000000000000000000000000000000000000000000000081525f602080830182905260018385018190526060808501879052855180840187528481526080860152855160028082529181018752939586959294929386939291908301908036833701905050905087818581518110611464576114646123af565b60200260200101906001600160a01b031690816001600160a01b03168152505086818481518110611497576114976123af565b6001600160a01b0392909216602092830291909101909101526040805160018082528183019092525f91816020015b6114f76040518060a001604052805f80191681526020015f81526020015f81526020015f8152602001606081525090565b8152602001906001900390816114c657905050905082815f8151811061151f5761151f6123af565b602002602001018190525073ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b031663f84d066e600183858e6040518563ffffffff1660e01b81526004016115719493929190612405565b5f604051808303815f875af115801561158c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526115b391908101906124f4565b85815181106115c4576115c46123af565b602002602001015195505050505050949350505050565b604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f90819081906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690633c04b54790602401602060405180830381865afa158015611666573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061168a9190612311565b604051632bfe485960e11b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201526001600160a01b0386811660248301529192507f0000000000000000000000000000000000000000000000000000000000000000909116906357fc90b290604401602060405180830381865afa15801561171c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117409190612311565b91505f61174d8284612595565b90506117656b033b2e3c9fd0803ce8000000826125c0565b93505f61177e6b033b2e3c9fd0803ce8000000836125d3565b11156117905761178d846125e6565b93505b5050915091565b6040516001600160a01b038381166024830152604482018390526117c891859182169063a9059cbb906064016110a2565b505050565b604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690633c04b54790602401602060405180830381865afa158015611854573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118789190612311565b90505f6118858383611a9f565b604051638459b43760e01b81529091506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690638459b437906118fa907f0000000000000000000000000000000000000000000000000000000000000000908a903090879060040161216f565b5f604051808303815f87803b158015611911575f80fd5b505af1158015611923573d5f803e3d5ffd5b5050604051631d0fe70360e21b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016925063743f9c0c9150611999907f0000000000000000000000000000000000000000000000000000000000000000908a9030908a9060040161216f565b5f604051808303815f87803b1580156119b0575f80fd5b505af11580156119c2573d5f803e3d5ffd5b505060405163ef693bed60e01b81526001600160a01b038881166004830152602482018890527f000000000000000000000000000000000000000000000000000000000000000016925063ef693bed9150604401610811565b5f611a2f6001600160a01b03841683611ab7565b905080515f14158015611a53575080806020019051810190611a519190612076565b155b156117c857604051635274afe760e01b81526001600160a01b038416600482015260240161043b565b5f611a96836b033b2e3c9fd0803ce8000000846001611ac4565b90505b92915050565b5f611a96836b033b2e3c9fd0803ce800000084611b11565b6060611a9683835f611bd1565b5f80611ad1868686611b11565b9050611adc83611c60565b8015611af757505f8480611af257611af26125ac565b868809115b1561095557611b07600182612210565b9695505050505050565b5f838302815f1985870982811083820303915050805f03611b4557838281611b3b57611b3b6125ac565b0492505050611bca565b808411611b655760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b606081471015611bf65760405163cd78605960e01b815230600482015260240161043b565b5f80856001600160a01b03168486604051611c1191906125fe565b5f6040518083038185875af1925050503d805f8114611c4b576040519150601f19603f3d011682016040523d82523d5f602084013e611c50565b606091505b5091509150611b07868383611c8c565b5f6002826003811115611c7557611c75612223565b611c7f9190612619565b60ff166001149050919050565b606082611ca157611c9c82611ce8565b611bca565b8151158015611cb857506001600160a01b0384163b155b15611ce157604051639996b31560e01b81526001600160a01b038516600482015260240161043b565b5080611bca565b805115611cf85780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b50565b5f8083601f840112611d24575f80fd5b50813567ffffffffffffffff811115611d3b575f80fd5b6020830191508360208260051b8501011115611d55575f80fd5b9250929050565b5f805f805f8060a08789031215611d71575f80fd5b86359550602087013594506040870135935060608701359250608087013567ffffffffffffffff811115611da3575f80fd5b611daf89828a01611d14565b979a9699509497509295939492505050565b5f805f60608486031215611dd3575f80fd5b505081359360208301359350604090920135919050565b5f805f8060608587031215611dfd575f80fd5b8435935060208501359250604085013567ffffffffffffffff811115611e21575f80fd5b611e2d87828801611d14565b95989497509550505050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715611e7657611e76611e39565b604052919050565b6001600160a01b0381168114611d11575f80fd5b8035611e9d81611e7e565b919050565b8015158114611d11575f80fd5b5f805f8084860360e0811215611ec3575f80fd5b6080811215611ed0575f80fd5b506040516080810181811067ffffffffffffffff82111715611ef457611ef4611e39565b6040528535611f0281611e7e565b81526020860135611f1281611ea2565b60208201526040860135611f2581611e7e565b60408201526060860135611f3881611ea2565b606082015293506080850135611f4d81611e7e565b9250611f5b60a08601611e92565b9396929550929360c00135925050565b5f60208284031215611f7b575f80fd5b5035919050565b5f805f8060608587031215611f95575f80fd5b8435935060208501359250604085013567ffffffffffffffff80821115611fba575f80fd5b818701915087601f830112611fcd575f80fd5b813581811115611fdb575f80fd5b886020828501011115611fec575f80fd5b95989497505060200194505050565b5f806040838503121561200c575f80fd5b50508035926020909101359150565b60ff861681526001600160a01b0385811660208301528416604082015260806060820181905281018290525f6001600160fb1b0383111561205a575f80fd5b8260051b808560a08501379190910160a0019695505050505050565b5f60208284031215612086575f80fd5b8151611bca81611ea2565b634e487b7160e01b5f52601160045260245ffd5b81810381811115611a9957611a99612091565b81516001600160a01b031681526020808301519082015260408083015190820152606080830151908201526080918201519181019190915260a00190565b5f5b838110156121105781810151838201526020016120f8565b50505f910152565b5f815180845261212f8160208601602086016120f6565b601f01601f19169290920160200192915050565b60018060a01b0385168152836020820152826040820152608060608201525f611b076080830184612118565b60ff9490941684526001600160a01b03928316602085015291166040830152606082015260800190565b5f60a082840312156121a9575f80fd5b60405160a0810181811067ffffffffffffffff821117156121cc576121cc611e39565b60405282356121da81611e7e565b80825250602083013560208201526040830135604082015260608301356060820152608083013560808201528091505092915050565b80820180821115611a9957611a99612091565b634e487b7160e01b5f52602160045260245ffd5b6002811061225357634e487b7160e01b5f52602160045260245ffd5b9052565b60e08152845160e08201525f6020860151612276610100840182612237565b5060408601516001600160a01b03908116610120840152606087015116610140830152608086015161016083015260a086015160c06101808401526122bf6101a0840182612118565b9150506122ff602083018680516001600160a01b039081168352602080830151151590840152604080830151909116908301526060908101511515910152565b60a082019390935260c0015292915050565b5f60208284031215612321575f80fd5b5051919050565b634e487b7160e01b5f52600160045260245ffd5b60ff861681526001600160a01b0385811660208084019190915290851660408301526060820184905260a06080830181905283519083018190525f918481019160c0850190845b8181101561239f57845183529383019391830191600101612383565b50909a9950505050505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f8151808452602080850194508084015f5b838110156123fa5781516001600160a01b0316875295820195908201906001016123d5565b509495945050505050565b5f60e082016124148388612237565b602060e08185015281875180845261010093508386019150838160051b87010193508289015f5b8281101561249d5787860360ff190184528151805187528581015186880152604080820151908801526060808201519088015260809081015160a09188018290529061248981890183612118565b97505050928401929084019060010161243b565b505050505082810360408401526124b481866123c3565b915050610955606083018480516001600160a01b039081168352602080830151151590840152604080830151909116908301526060908101511515910152565b5f6020808385031215612505575f80fd5b825167ffffffffffffffff8082111561251c575f80fd5b818501915085601f83011261252f575f80fd5b81518181111561254157612541611e39565b8060051b9150612552848301611e4d565b818152918301840191848101908884111561256b575f80fd5b938501935b8385101561258957845182529385019390850190612570565b98975050505050505050565b8082028115828204841417611a9957611a99612091565b634e487b7160e01b5f52601260045260245ffd5b5f826125ce576125ce6125ac565b500490565b5f826125e1576125e16125ac565b500690565b5f600182016125f7576125f7612091565b5060010190565b5f825161260f8184602087016120f6565b9190910192915050565b5f60ff83168061262b5761262b6125ac565b8060ff8416069150509291505056fea2646970667358221220478ac36d4f71ffddc6fd7e13419bb09c7e0b65aa78644bf43405de4c9e4aab0764736f6c63430008150033000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f5000000000000000000000000e21ae2d45dedf8dee2d854774a904d33b8700e78000000000000000000000000f98248f0da9d51d827a3c42d608acf65c77bd76a00000000000000000000000020e068d76f9e90b90604500b84c7e19dcb923e7eab99a3e856deb448ed99713dfce62f937e2d4d740000000000000000000001180000000000000000000000004200000000000000000000000000000000000006
Deployed Bytecode
0x6080604052600436106100f2575f3560e01c8063ad5c464811610087578063ebc9b94d11610057578063ebc9b94d14610351578063ec342ad014610370578063ed0cee97146103a3578063f676c6a4146103e8575f80fd5b8063ad5c4648146102ad578063e54a55b6146102e0578063e7f6d7c4146102ff578063e9cbafb014610332575f80fd5b80637535d246116100c25780637535d246146101fb5780637f9681481461022e57806396c7525914610261578063aac56b5814610280575f80fd5b80630cc20584146101465780630eb3e108146101595780631bb7cc991461017857806350c6cf88146101c8575f80fd5b3661014257336001600160a01b037f0000000000000000000000004200000000000000000000000000000000000006161461014057604051637c56635360e01b815260040160405180910390fd5b005b5f80fd5b610140610154366004611d5c565b61041b565b348015610164575f80fd5b50610140610173366004611dc1565b6106ff565b348015610183575f80fd5b506101ab7f000000000000000000000000f98248f0da9d51d827a3c42d608acf65c77bd76a81565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156101d3575f80fd5b506101ab7f00000000000000000000000004c0599ae5a44757c0af6f9ec3b93da8976c150a81565b348015610206575f80fd5b506101ab7f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f581565b348015610239575f80fd5b506101ab7f000000000000000000000000e21ae2d45dedf8dee2d854774a904d33b8700e7881565b34801561026c575f80fd5b5061014061027b366004611dea565b610847565b34801561028b575f80fd5b5061029f61029a366004611eaf565b610948565b6040519081526020016101bf565b3480156102b8575f80fd5b506101ab7f000000000000000000000000420000000000000000000000000000000000000681565b3480156102eb575f80fd5b506101406102fa366004611f6b565b61095e565b34801561030a575f80fd5b5061029f7fab99a3e856deb448ed99713dfce62f937e2d4d7400000000000000000000011881565b34801561033d575f80fd5b5061014061034c366004611f82565b610b61565b34801561035c575f80fd5b5061014061036b366004611ffb565b611028565b34801561037b575f80fd5b506101ab7f000000000000000000000000420000000000000000000000000000000000000681565b3480156103ae575f80fd5b506103d67f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff90911681526020016101bf565b3480156103f3575f80fd5b506101ab7f00000000000000000000000020e068d76f9e90b90604500b84c7e19dcb923e7e81565b824281116104445760405163356dfb6f60e01b8152600481018290526024015b60405180910390fd5b82827f000000000000000000000000f98248f0da9d51d827a3c42d608acf65c77bd76a6001600160a01b031663b5406b3d7f0000000000000000000000000000000000000000000000000000000000000000333386866040518663ffffffff1660e01b81526004016104ba95949392919061201b565b602060405180830381865afa1580156104d5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104f99190612076565b5061052f6001600160a01b037f00000000000000000000000004c0599ae5a44757c0af6f9ec3b93da8976c150a1633308c61106d565b5f61053a8a8a6120a5565b9050805f036105575761055133308b5f60016110d4565b506106f4565b61058d6040518060a001604052805f6001600160a01b031681526020015f81526020015f81526020015f81526020015f81525090565b60408051608081018252308082525f602083018190529282015260608101829052906105fb827f00000000000000000000000042000000000000000000000000000000000000067f00000000000000000000000004c0599ae5a44757c0af6f9ec3b93da8976c150a876113d6565b338452602084018e9052604084018c9052606084018190526080840185905290505f807f00000000000000000000000000000000000000000000000000000000000000011561064c5782915061064f565b50815b7f00000000000000000000000020e068d76f9e90b90604500b84c7e19dcb923e7e6001600160a01b031663490e6cbc3084848960405160200161069291906120b8565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016106c09493929190612143565b5f604051808303815f87803b1580156106d7575f80fd5b505af11580156106e9573d5f803e3d5ffd5b505050505050505050505b505050505050505050565b804281116107235760405163356dfb6f60e01b81526004810182905260240161043b565b5f19830361073857610734336115db565b5092505b8215610841575f807f00000000000000000000000000000000000000000000000000000000000000011561076e57849150610771565b50835b7f00000000000000000000000020e068d76f9e90b90604500b84c7e19dcb923e7e6001600160a01b031663490e6cbc3084846040518060a00160405280336001600160a01b031681526020015f81526020018c81526020018b81526020015f8152506040516020016107e391906120b8565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016108119493929190612143565b5f604051808303815f87803b158015610828575f80fd5b505af115801561083a573d5f803e3d5ffd5b5050505050505b50505050565b81817f000000000000000000000000f98248f0da9d51d827a3c42d608acf65c77bd76a6001600160a01b031663b5406b3d7f0000000000000000000000000000000000000000000000000000000000000000333386866040518663ffffffff1660e01b81526004016108bd95949392919061201b565b602060405180830381865afa1580156108d8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108fc9190612076565b506109326001600160a01b037f00000000000000000000000004c0599ae5a44757c0af6f9ec3b93da8976c150a1633308961106d565b6109403333888860016110d4565b505050505050565b5f610955858585856113d6565b95945050505050565b5f80610969336115db565b90925090506109a36001600160a01b037f00000000000000000000000042000000000000000000000000000000000000061633308561106d565b604051638459b43760e01b81526001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f51690638459b43790610a15907f00000000000000000000000000000000000000000000000000000000000000009033903090879060040161216f565b5f604051808303815f87803b158015610a2c575f80fd5b505af1158015610a3e573d5f803e3d5ffd5b5050604051631d0fe70360e21b81526001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f516925063743f9c0c9150610ab4907f00000000000000000000000000000000000000000000000000000000000000009033903090899060040161216f565b5f604051808303815f87803b158015610acb575f80fd5b505af1158015610add573d5f803e3d5ffd5b505060405163ef693bed60e01b8152336004820152602481018690527f000000000000000000000000e21ae2d45dedf8dee2d854774a904d33b8700e786001600160a01b0316925063ef693bed91506044015f604051808303815f87803b158015610b46575f80fd5b505af1158015610b58573d5f803e3d5ffd5b50505050505050565b336001600160a01b037f00000000000000000000000020e068d76f9e90b90604500b84c7e19dcb923e7e1614610bac57604051634c04358d60e11b815233600482015260240161043b565b5f610bb982840184612199565b60408051608081018252308082525f602083018190529282015260608101829052919250610be78688612210565b608084015190915015610dfa5760808301518351604085015160608601515f610c108683612210565b905082811115610c3d57604051634245776b60e11b8152600481018290526024810184905260440161043b565b6040805160c081019091527fab99a3e856deb448ed99713dfce62f937e2d4d7400000000000000000000011881525f9060208101600181526020017f00000000000000000000000042000000000000000000000000000000000000066001600160a01b031681526020017f00000000000000000000000004c0599ae5a44757c0af6f9ec3b93da8976c150a6001600160a01b0316815260200187815260200160405180602001604052805f81525081525090505f73ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b03166352bbbe29838b5f19426001610d259190612210565b6040518563ffffffff1660e01b8152600401610d449493929190612257565b6020604051808303815f875af1158015610d60573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d849190612311565b905089606001518114610d9957610d99612328565b5f878b60200151610daa9190612210565b9050610db9873083875f6110d4565b610ded6001600160a01b037f0000000000000000000000004200000000000000000000000000000000000006163386611797565b5050505050505050610b58565b5f818460600151610e0b9190612210565b90505f610e5a847f00000000000000000000000004c0599ae5a44757c0af6f9ec3b93da8976c150a7f0000000000000000000000004200000000000000000000000000000000000006856113d6565b604086015190915080821115610e8d57604051634245776b60e11b8152600481018390526024810182905260440161043b565b610ea0865f0151308489606001516117cd565b6040805160c081019091527fab99a3e856deb448ed99713dfce62f937e2d4d7400000000000000000000011881525f9060208101600181526020017f00000000000000000000000004c0599ae5a44757c0af6f9ec3b93da8976c150a6001600160a01b031681526020017f00000000000000000000000042000000000000000000000000000000000000066001600160a01b0316815260200185815260200160405180602001604052805f815250815250905073ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b03166352bbbe2982885f19426001610f879190612210565b6040518563ffffffff1660e01b8152600401610fa69493929190612257565b6020604051808303815f875af1158015610fc2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fe69190612311565b5061101b6001600160a01b037f0000000000000000000000004200000000000000000000000000000000000006163386611797565b5050505050505050505050565b61105d6001600160a01b037f00000000000000000000000042000000000000000000000000000000000000061633308561106d565b611069333383856117cd565b5050565b6040516001600160a01b0384811660248301528381166044830152606482018390526108419186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611a1b565b604051633b4da69f60e01b8152306004820152602481018490527f000000000000000000000000e21ae2d45dedf8dee2d854774a904d33b8700e786001600160a01b031690633b4da69f906044015f604051808303815f87803b158015611139575f80fd5b505af115801561114b573d5f803e3d5ffd5b50506001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f516915063918a2f4290507f00000000000000000000000000000000000000000000000000000000000000008730875f6040519080825280602002602001820160405280156111ce578160200160208202803683370190505b506040518663ffffffff1660e01b81526004016111ef95949392919061233c565b5f604051808303815f87803b158015611206575f80fd5b505af1158015611218573d5f803e3d5ffd5b50505050815f03156113cf57604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f907f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f56001600160a01b031690633c04b54790602401602060405180830381865afa1580156112ab573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112cf9190612311565b90505f808360018111156112e5576112e5612223565b036112fb576112f48483611a7c565b9050611308565b6113058483611a9f565b90505b6001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f516639306f2f87f00000000000000000000000000000000000000000000000000000000000000008989855f604051908082528060200260200182016040528015611385578160200160208202803683370190505b506040518663ffffffff1660e01b81526004016113a695949392919061233c565b5f604051808303815f87803b1580156113bd575f80fd5b505af115801561101b573d5f803e3d5ffd5b5050505050565b6040805160a0810182527fab99a3e856deb448ed99713dfce62f937e2d4d7400000000000000000000011881525f602080830182905260018385018190526060808501879052855180840187528481526080860152855160028082529181018752939586959294929386939291908301908036833701905050905087818581518110611464576114646123af565b60200260200101906001600160a01b031690816001600160a01b03168152505086818481518110611497576114976123af565b6001600160a01b0392909216602092830291909101909101526040805160018082528183019092525f91816020015b6114f76040518060a001604052805f80191681526020015f81526020015f81526020015f8152602001606081525090565b8152602001906001900390816114c657905050905082815f8151811061151f5761151f6123af565b602002602001018190525073ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b031663f84d066e600183858e6040518563ffffffff1660e01b81526004016115719493929190612405565b5f604051808303815f875af115801561158c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526115b391908101906124f4565b85815181106115c4576115c46123af565b602002602001015195505050505050949350505050565b604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f90819081906001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f51690633c04b54790602401602060405180830381865afa158015611666573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061168a9190612311565b604051632bfe485960e11b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201526001600160a01b0386811660248301529192507f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f5909116906357fc90b290604401602060405180830381865afa15801561171c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117409190612311565b91505f61174d8284612595565b90506117656b033b2e3c9fd0803ce8000000826125c0565b93505f61177e6b033b2e3c9fd0803ce8000000836125d3565b11156117905761178d846125e6565b93505b5050915091565b6040516001600160a01b038381166024830152604482018390526117c891859182169063a9059cbb906064016110a2565b505050565b604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f907f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f56001600160a01b031690633c04b54790602401602060405180830381865afa158015611854573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118789190612311565b90505f6118858383611a9f565b604051638459b43760e01b81529091506001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f51690638459b437906118fa907f0000000000000000000000000000000000000000000000000000000000000000908a903090879060040161216f565b5f604051808303815f87803b158015611911575f80fd5b505af1158015611923573d5f803e3d5ffd5b5050604051631d0fe70360e21b81526001600160a01b037f00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f516925063743f9c0c9150611999907f0000000000000000000000000000000000000000000000000000000000000000908a9030908a9060040161216f565b5f604051808303815f87803b1580156119b0575f80fd5b505af11580156119c2573d5f803e3d5ffd5b505060405163ef693bed60e01b81526001600160a01b038881166004830152602482018890527f000000000000000000000000e21ae2d45dedf8dee2d854774a904d33b8700e7816925063ef693bed9150604401610811565b5f611a2f6001600160a01b03841683611ab7565b905080515f14158015611a53575080806020019051810190611a519190612076565b155b156117c857604051635274afe760e01b81526001600160a01b038416600482015260240161043b565b5f611a96836b033b2e3c9fd0803ce8000000846001611ac4565b90505b92915050565b5f611a96836b033b2e3c9fd0803ce800000084611b11565b6060611a9683835f611bd1565b5f80611ad1868686611b11565b9050611adc83611c60565b8015611af757505f8480611af257611af26125ac565b868809115b1561095557611b07600182612210565b9695505050505050565b5f838302815f1985870982811083820303915050805f03611b4557838281611b3b57611b3b6125ac565b0492505050611bca565b808411611b655760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b606081471015611bf65760405163cd78605960e01b815230600482015260240161043b565b5f80856001600160a01b03168486604051611c1191906125fe565b5f6040518083038185875af1925050503d805f8114611c4b576040519150601f19603f3d011682016040523d82523d5f602084013e611c50565b606091505b5091509150611b07868383611c8c565b5f6002826003811115611c7557611c75612223565b611c7f9190612619565b60ff166001149050919050565b606082611ca157611c9c82611ce8565b611bca565b8151158015611cb857506001600160a01b0384163b155b15611ce157604051639996b31560e01b81526001600160a01b038516600482015260240161043b565b5080611bca565b805115611cf85780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b50565b5f8083601f840112611d24575f80fd5b50813567ffffffffffffffff811115611d3b575f80fd5b6020830191508360208260051b8501011115611d55575f80fd5b9250929050565b5f805f805f8060a08789031215611d71575f80fd5b86359550602087013594506040870135935060608701359250608087013567ffffffffffffffff811115611da3575f80fd5b611daf89828a01611d14565b979a9699509497509295939492505050565b5f805f60608486031215611dd3575f80fd5b505081359360208301359350604090920135919050565b5f805f8060608587031215611dfd575f80fd5b8435935060208501359250604085013567ffffffffffffffff811115611e21575f80fd5b611e2d87828801611d14565b95989497509550505050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715611e7657611e76611e39565b604052919050565b6001600160a01b0381168114611d11575f80fd5b8035611e9d81611e7e565b919050565b8015158114611d11575f80fd5b5f805f8084860360e0811215611ec3575f80fd5b6080811215611ed0575f80fd5b506040516080810181811067ffffffffffffffff82111715611ef457611ef4611e39565b6040528535611f0281611e7e565b81526020860135611f1281611ea2565b60208201526040860135611f2581611e7e565b60408201526060860135611f3881611ea2565b606082015293506080850135611f4d81611e7e565b9250611f5b60a08601611e92565b9396929550929360c00135925050565b5f60208284031215611f7b575f80fd5b5035919050565b5f805f8060608587031215611f95575f80fd5b8435935060208501359250604085013567ffffffffffffffff80821115611fba575f80fd5b818701915087601f830112611fcd575f80fd5b813581811115611fdb575f80fd5b886020828501011115611fec575f80fd5b95989497505060200194505050565b5f806040838503121561200c575f80fd5b50508035926020909101359150565b60ff861681526001600160a01b0385811660208301528416604082015260806060820181905281018290525f6001600160fb1b0383111561205a575f80fd5b8260051b808560a08501379190910160a0019695505050505050565b5f60208284031215612086575f80fd5b8151611bca81611ea2565b634e487b7160e01b5f52601160045260245ffd5b81810381811115611a9957611a99612091565b81516001600160a01b031681526020808301519082015260408083015190820152606080830151908201526080918201519181019190915260a00190565b5f5b838110156121105781810151838201526020016120f8565b50505f910152565b5f815180845261212f8160208601602086016120f6565b601f01601f19169290920160200192915050565b60018060a01b0385168152836020820152826040820152608060608201525f611b076080830184612118565b60ff9490941684526001600160a01b03928316602085015291166040830152606082015260800190565b5f60a082840312156121a9575f80fd5b60405160a0810181811067ffffffffffffffff821117156121cc576121cc611e39565b60405282356121da81611e7e565b80825250602083013560208201526040830135604082015260608301356060820152608083013560808201528091505092915050565b80820180821115611a9957611a99612091565b634e487b7160e01b5f52602160045260245ffd5b6002811061225357634e487b7160e01b5f52602160045260245ffd5b9052565b60e08152845160e08201525f6020860151612276610100840182612237565b5060408601516001600160a01b03908116610120840152606087015116610140830152608086015161016083015260a086015160c06101808401526122bf6101a0840182612118565b9150506122ff602083018680516001600160a01b039081168352602080830151151590840152604080830151909116908301526060908101511515910152565b60a082019390935260c0015292915050565b5f60208284031215612321575f80fd5b5051919050565b634e487b7160e01b5f52600160045260245ffd5b60ff861681526001600160a01b0385811660208084019190915290851660408301526060820184905260a06080830181905283519083018190525f918481019160c0850190845b8181101561239f57845183529383019391830191600101612383565b50909a9950505050505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f8151808452602080850194508084015f5b838110156123fa5781516001600160a01b0316875295820195908201906001016123d5565b509495945050505050565b5f60e082016124148388612237565b602060e08185015281875180845261010093508386019150838160051b87010193508289015f5b8281101561249d5787860360ff190184528151805187528581015186880152604080820151908801526060808201519088015260809081015160a09188018290529061248981890183612118565b97505050928401929084019060010161243b565b505050505082810360408401526124b481866123c3565b915050610955606083018480516001600160a01b039081168352602080830151151590840152604080830151909116908301526060908101511515910152565b5f6020808385031215612505575f80fd5b825167ffffffffffffffff8082111561251c575f80fd5b818501915085601f83011261252f575f80fd5b81518181111561254157612541611e39565b8060051b9150612552848301611e4d565b818152918301840191848101908884111561256b575f80fd5b938501935b8385101561258957845182529385019390850190612570565b98975050505050505050565b8082028115828204841417611a9957611a99612091565b634e487b7160e01b5f52601260045260245ffd5b5f826125ce576125ce6125ac565b500490565b5f826125e1576125e16125ac565b500690565b5f600182016125f7576125f7612091565b5060010190565b5f825161260f8184602087016120f6565b9190910192915050565b5f60ff83168061262b5761262b6125ac565b8060ff8416069150509291505056fea2646970667358221220478ac36d4f71ffddc6fd7e13419bb09c7e0b65aa78644bf43405de4c9e4aab0764736f6c63430008150033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f5000000000000000000000000e21ae2d45dedf8dee2d854774a904d33b8700e78000000000000000000000000f98248f0da9d51d827a3c42d608acf65c77bd76a00000000000000000000000020e068d76f9e90b90604500b84c7e19dcb923e7eab99a3e856deb448ed99713dfce62f937e2d4d740000000000000000000001180000000000000000000000004200000000000000000000000000000000000006
-----Decoded View---------------
Arg [0] : _ilkIndex (uint8): 0
Arg [1] : _ionPool (address): 0x00000000000fA8e0FD26b4554d067CF1856De7F5
Arg [2] : _gemJoin (address): 0xe21ae2d45dEDF8dEE2D854774a904d33b8700E78
Arg [3] : _whitelist (address): 0xf98248f0dA9D51d827A3C42d608acF65c77BD76A
Arg [4] : _wstEthUniswapPool (address): 0x20E068D76f9E90b90604500B84c7e19dCB923e7e
Arg [5] : _balancerPoolId (bytes32): 0xab99a3e856deb448ed99713dfce62f937e2d4d74000000000000000000000118
Arg [6] : _weth (address): 0x4200000000000000000000000000000000000006
-----Encoded View---------------
7 Constructor Arguments found :
Arg [0] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [1] : 00000000000000000000000000000000000fa8e0fd26b4554d067cf1856de7f5
Arg [2] : 000000000000000000000000e21ae2d45dedf8dee2d854774a904d33b8700e78
Arg [3] : 000000000000000000000000f98248f0da9d51d827a3c42d608acf65c77bd76a
Arg [4] : 00000000000000000000000020e068d76f9e90b90604500b84c7e19dcb923e7e
Arg [5] : ab99a3e856deb448ed99713dfce62f937e2d4d74000000000000000000000118
Arg [6] : 0000000000000000000000004200000000000000000000000000000000000006
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 ]
[ 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.